Home > Web Front-end > JS Tutorial > body text

javascript interesting and weird array_javascript skills

WBOY
Release: 2016-05-16 18:54:42
Original
826 people have browsed it

Years ago, when I was rewriting the membership card script in Taobao Wangpu, I accidentally discovered an interesting thing. The code is similar:

Copy code The code is 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}

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
Copy the code The code is as follows:

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

Copy code The code is as follows:

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:
Copy the code The code is as follows:

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:

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!