Although not very common, we can indeed add attributes with numbers as attribute names to objects:
Copy Code code as follows:
var obj = {};
Obj[0] = 1;
OBJ[1] = 2;
This object is not an array type, so is there any way to convert it to a group type? The jquery code uses Array.prototype.slice to convert this object to an array, but I tried it several times, just not:
Copy Code code as follows:
var obj = {};
Obj[0] = 1;
OBJ[1] = 2;
Alert (Array.prototype.slice.call (obj));
The above code in IE directly under the error, in Firefox, although there is no error, the output is empty. It is said that the conversion has failed. The problem with this built-in approach is better to check it out.
ECMA-262, the first two steps of the slice method's execution process are as follows:
Copy Code code as follows:
1. Let A is a new array created as if by the expression new array ().
2. Call the [[[Get]] ' method of ' This object with argument ' length '.
The parameter length is mentioned here. The Obj object has a numeric index but does not have a length property. The problem is this: the slice method does not know the length of the object. Simply modify the code to add the Length property:
Copy Code code as follows:
var obj = {};
Obj[0] = 1;
OBJ[1] = 2;
Obj.length = 2;
Alert (Array.prototype.slice.call (obj));
The output is "1,2" and the copy is successful. Does that mean that you can convert an array if you call the slice method with the numeric index and length property ?
This law is set up in most browsers. However, in IE environment, the collection of DOM elements such as htmlcollection , even with the above features, also complains when calling Slice.