Simulate hashtable in JavaScript to quickly search for Arrays
In the face of an array, sometimes you want to directly access a specific element, rather than searching for the entire array loop. Think about hashtable, which is convenient to query in C #. javascript can simulate this technology to quickly search for arrays.
In JavaScript, array is treated as an object, so that you can define properties for it without affecting the original data in the array. The attribute can be referenced by its name.
The key to implementation: For an existing array, We must generate a Unique Identifier value for each of its elements to effectively access all elements.
As an example, first create a custom object "employee" with two attributes "Name and" age.
Function employee (name, age)
{
This. Name = Name;
This. Age = age;
}
Create an array:
VaR employees = new array ();
Employees [employees. Length] = new employee ("Anders", 25 );
Employees [employees. Length] = new employee ("Andrew", 27 );
Employees [employees. Length] = new employee ("bill", 45 );
Simulate hashtable:
For (VAR I = 0; I <employees. length; I ++)
{
Employees [employees [I]. Name] = employees [I];
}
Here, the name attribute of employees [I] is used as the key of hashtable, and employees [I] is used as the value, so that you can quickly search by name;
For example, VAR billsage = employees ["bill"]. Age;
Note: In the array defined above, it is difficult to avoid two elements with duplicate names. In this case, the problem will occur, and the added objects will overwrite the original objects. Therefore, we should try to ensure the uniqueness of the variable value used as the key of hashtable so that each element can be accessed. If one attribute of an object cannot be unique, consider the merging values of multiple attributes.