Home > Web Front-end > JS Tutorial > Convert objects with numeric attribute names to arrays in js_javascript tips

Convert objects with numeric attribute names to arrays in js_javascript tips

WBOY
Release: 2016-05-16 18:09:39
Original
1187 people have browsed it

Although it is not commonly used, we can indeed add attributes with numbers as attribute names to objects:

Copy code 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? The jQuery code uses Array.prototype.slice to convert this kind of object into an array, but I tried several times and it just didn’t work:
Copy code 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 under IE. Although no error is reported under Firefox, the output content is empty. In other words, the conversion failed. For problems with this built-in method, it is best to check ECMA-262. The first two steps of the execution process of the slice method are as follows:
Copy code 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 parameter length is mentioned here. Although the obj object has a numeric index, it does not have a length attribute. Actually, that's the problem: the slice method doesn't know the length of this object. Simply modify the code and add the length attribute:
Copy the code 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", and the copy is successful. Does that mean that can be converted into an array as long as this when calling the slice method has a numeric index and a length attribute? .

This law holds true in most browsers. However, in the IE environment, for a collection of DOM elements such as HtmlCollection, even if it has the above characteristics, it will report an error when calling slice.

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