Although the key of this set can only be of the String type, unlike various collection classes in Java that can use various objects as keys, it is enough to implement general client JS functions. Similarly, because all internal JS objects inherit from Object objects, in fact, JS Array objects can also use strings as the subscript of arrays, just like the Array variables in PHP. From toushi.
An array is an internal object provided by JavaScript. It is a standard set. We can add (push), delete (shift) elements, we can also traverse the elements in the for loop, so can we have other sets in addition to arrays in JavaScript?
Because of the language features of JavaScript, We can dynamically add and delete attributes to common objects. Therefore, objects can also be seen as a special set of JS. The following compares the features of Array and Object:
Array:
New: var ary = new Array (); or var ary = [];
Added: ary. push (value );
Delete: delete ary [n];
Traversal: for (var I = 0; I <ary. length; ++ I) ary [I];
Object:
New: var obj = new Object (); or var obj = {};
Added: obj [key] = value; (key is string)
Delete: delete obj [key];
Traversal: for (var key in obj) obj [key];
From the above comparison, we can see that the Object can be used as a set. in the use of the Popup window to create an infinitely webpage menu (3), I introduced the _ MenuCache __implemented by Eric __, it is also a simulated set object.
If we want to retrieve a specified value in Array, We need to traverse the entire Array:
Copy codeThe Code is as follows:
Var keyword =;
For (var I = 0; I <ary. length; ++ I)
{
If (ary [I] = keyword)
{
// Todo
}
}
However, to retrieve a specified key entry in an Object, you only need to use:
Var key = '';
Var value = obj [key];
// Todo
This feature of the Object can be used to efficiently retrieve the string set of Unique. The time complexity of traversing the Array is O (n), and the time complexity of traversing the Object is O (1 ). Although the for search cost for 10000 sets is dozens of ms, if it is 1000*1000 queries or more, the advantages of using objects are shown. Before that, I made a mapping to map 100 Unique characters to 1000 string arrays, which took 25-30 s! Later, I changed the for traversal to the member reference of the Object simulation set. The same data volume mapping takes only 1.7-2 s !!!
For the collection traversal efficiency (from high to low): var value = obj [key];> for (;)> for (in ). The worst efficiency is for (in). If the set is too large, do not use for (in) traversal.