Simulate hashtable in JavaScript to quickly search for Arrays

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.