Years ago, when I was rewriting the membership card script in Taobao Wangpu, I accidentally discovered an interesting thing. The code is similar:
var associative_array = new Array();
associative_array["one"] = "1";
associative_array["two"] = "2";
associative_array["three"] = "3";
if(associative_array.length > ; 0)
{ // to do}
You will find that associate_array.length is always equal to 0, which was a bit confusing at the time. Later I realized that this is just like everyone thinks that IE supports the CSS attribute display:inline -block is the same, purely coincidence and misunderstanding.
Actually (quoted from 《JavaScript “Associative Arrays” Considered Harmful”):
JavaScript arrays (which are meant to be numeric) are often used to hold key/value pairs. This is bad practice. Object should be used instead.
//General idea: Arrays only support numbers, and key-value correspondence is used on objects.
There is no way to specify string keys in an array constructor. //String key values cannot be defined in the array constructor
There is no way to specify string keys in an array literal . //String keys cannot be defined in array literals
Array.length does not count them as items. // Array.length does not count string keys
Further peek into the array:
1. The array can be automatically resized according to the assigned value
var ar = [];
ar[2] = 1;
alert(ar.length)
It is found that the length of this array is 3, just like an initialized Same as array. All array objects without assignment will be defined as undefined.
Extended reading:
2. You can use the "The Miller Device" method to determine whether it is an array
function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]';}
" The wonderful use of "The Miller Device" is not only to determine the array:
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: