Years ago in the rewrite Taobao shopping card script, inadvertently found an interesting thing. The code is similar:
Copy Code code as follows:
var associative_array = new Array ();
associative_array["one"] = "1";
Associative_array["two"] = "2";
Associative_array["three"] = "3";
if (Associative_array.length > 0)
{//To do}
Will find that associative_array.length is always equal to 0, then a bit confused, and then know that this is like we think IE support CSS properties display:inline-block like, pure coincidence and misunderstanding.
In fact (citing " JavaScript" associative Arrays "considered harmful"):
JavaScript arrays (which are meant to is numeric) are often to used hold. This is bad practice. Object should be used instead.
The array only supports numbers, and the key values correspond to the objects.
There is no way to specify string keys in an array constructor. Cannot define string key values in array constructors
There is no way to specify string keys in an array literal. Cannot define string key value in array literal
Array.Length does not count them as items. Array.Length does not compute string key values
Further prying arrays:
1, the array can be automatically adjusted according to the value assigned to size
Copy Code code as follows:
var ar = [];
AR[2] = 1;
Alert (ar.length)
The length of this array is found to be 3, just like an initialized array. All of the array objects that are not assigned are defined as undefined.
Extended reading:
2, you can use the "the Miller Device" method to determine whether the array
Copy Code code as follows:
function IsArray (o) {return Object.prototype.toString.call (o) = = ' [Object Array] ';}
"The Miller Device" is not just about judging arrays:
Copy Code code as follows:
The var is = {
Types: ["Array", "RegExp", "Date", "number", "String", "Object"]
};
for (Var i=0,c;c=is.types[i++];) {
IS[C] = (function (type) {
return function (obj) {
return Object.prototype.toString.call (obj) = = "[Object" +type+ "]";
}
}) (c);
}
Extended reading:
- "The Miller Device"
- "isarray:why is it" it so bloody hard.