Array is an internal object provided by JavaScript. It is a standard collection. We can add (push) and delete (shift) the elements in it. We can also traverse the elements in it through a for loop. In addition to the array, we also have Can there be other collections?
Due to the language features of JavaScript, we can dynamically add and delete properties to general objects. So Object can also be regarded as a special collection of JS. Let’s compare the characteristics of Array and Object:
Array:
New: var ary = new Array(); or var ary = [];
Add: 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 = {};
Add: obj[key] = value; (key is string)
Delete: delete obj[key];
Traverse: for (var key in obj) obj[key];
From above From the comparison, we can see that Object can be used as a collection. In using the Popup window to create an infinite Web page menu (3), I introduced the __MenuCache__ implemented by Eric, which is also a simulated collection object.
If we want to retrieve a specified value in Array, we need to traverse the entire array:
ebf969465e22595a9eff9ac99a99bbbeObject It can be used to efficiently retrieve Unique string collections. The time complexity of traversing Array is O(n), while the time complexity of traversing Object is O(1). Although the cost of for retrieval for 10,000 collections is only tens of ms, if it is 1,000*1,000 retrievals or more, the advantages of using Object will be immediately apparent. Before that, I did a mapping, mapping 100 Unique characters to 1000 string arrays, which took 25-30 seconds! Later, I changed the for traversal to the member reference of the Object simulated collection, and the same amount of data was mapped , it takes only 1.7-2s!!!
For the traversal efficiency of the collection (from high to low): var value = obj[key]; > for ( ; ; ) > for ( in ). The least efficient one is for(in). If the collection is too large, try not to use for(in) to traverse.
The above is the content of the Javascript tutorial about arrays, collections and efficiency in JavaScript. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!