SoFunction
Updated on 2025-04-03

When the object has no length attribute, it cannot be converted into a pseudo-array in IE6/IE7 (ArrayLike)

Sometimes you need to convert an array into a pseudo-array (ArrayLike), as follows
Copy the codeThe code is as follows:

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

IE8/9/Firefox/Safari/Chrome The obj key and its value pop up in turn. That is, it can be converted into ArrayLike.
But under IE6/7, it cannot be used, and no information is output to indicate that obj is still an empty object.
If you add a length attribute to obj, the situation will be different
Copy the codeThe code is as follows:

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

This time, key and value popped up in IE6/7 (all browsers), which can be converted into ArrayLike
Note that length can only be assigned to 0 instead of its value, otherwise the resulting object key and value will not correspond one by one.
Copy the codeThe code is as follows:

var ary = ['one','two','three'];
var obj = {length:2}; // There is length, non-zero value
(obj, ary);
for(var i in obj){
alert(i + ': ' + obj[i]);
}