In js, objects with numeric attribute names are converted into arrays. Although not commonly used, we can indeed add attributes with numbers as attribute names to objects, although they are not commonly used, however, we can add the attribute named "Number" to the object:
The Code is as follows:
Var obj = {};
Obj [0] = 1;
Obj [1] = 2;
This object is not an array type. Is there any way to convert it to an array type? In jQuery code, Array. prototype. slice is used to convert this object into an Array. However, I tried it several times, but it won't work:
The Code is as follows:
Var obj = {};
Obj [0] = 1;
Obj [1] = 2;
Alert (Array. prototype. slice. call (obj ));
The above Code directly reports an error in IE. Although no error is reported in Firefox, the output content is empty. That is to say, the conversion fails. It is best to check the problem of this built-in method.
ECMA-262The first two steps of the slice method execution process are as follows:
The Code is as follows:
1. Let A be a new array created as if by the expression new Array ().
2. Call the [[Get] method of this object with argument "length ".
The length parameter is mentioned here. Although the obj object has a digital index, it does not have the length attribute. The problem is that the slice method does not know the object length. Simply modify the code and add the length attribute:
The Code is as follows:
Var obj = {};
Obj [0] = 1;
Obj [1] = 2;
Obj. length = 2;
Alert (Array. prototype. slice. call (obj ));
The output content is "1, 2". Copied successfully. Does that explain,This can be converted to an array as long as the slice method has the numeric index and length attributes.What about it ?.
This law is true in most browsers. However, in the IE environmentHtmlCollectionEven if such a DOM Element Set has the preceding features, it reports an error when calling slice.