Home  >  Article  >  Web Front-end  >  When an object has no length attribute, it cannot be converted into a pseudo array (ArrayLike) in IE6/IE7_javascript tips

When an object has no length attribute, it cannot be converted into a pseudo array (ArrayLike) in IE6/IE7_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:04:191154browse

Sometimes it is necessary to convert an array into a pseudo array (ArrayLike), as follows

Copy the code The code is as follows:

var ary = ['one','two','three'];
var obj = {}; // No length attribute
Array.prototype.push.apply(obj, ary);
for(var i in obj){
alert(i ': ' obj[i]);
}

IE8/9/Firefox/Safari/Chrome pops up obj in sequence The key and its value. That can be converted into ArrayLike.
But this is not possible under IE6/7. No information is output to indicate that obj is still an empty object.
If you add a length attribute to obj, the situation is different
Copy code The code is as follows:

var ary = ['one','two','three'];
var obj = {length:0}; // There is length and the value is 0
Array.prototype.push.apply( obj, ary);
for(var i in obj){
alert(i ': ' obj[i]);
}

This time IE6/7( Key and its value pop up in all browsers), and they can be converted into ArrayLike
Note that length can only be assigned a value of 0 instead of other values, otherwise the obtained object key and value will not correspond one to one.
Copy code The code is as follows:

var ary = ['one','two', 'three'];
var obj = {length:2}; // There is length, non-zero value
Array.prototype.push.apply(obj, ary);
for(var i in obj ){
alert(i ': ' obj[i]);
}
Statement:
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