Home >Web Front-end >JS Tutorial >js multiple methods to convert pseudo array to standard array

js multiple methods to convert pseudo array to standard array

巴扎黑
巴扎黑Original
2016-12-06 10:15:051520browse

In js, arrays are special objects. Arrays have all the properties of objects. Arrays represent collections of ordered data, while objects represent collections of unordered data.

What is a pseudo array? Of course it is also an object. Pseudo arrays generally have the following characteristics:

Storage data by index;

Has the length attribute;

No push, shift, pop and other methods of the array;

The arguments object of the function, as well as the NodeList objects returned by getElementsByTagName, ele.childNodes, etc., or some customized objects, can all be pseudo arrays.

We can convert pseudo arrays into standard arrays in the following ways:

Use Array.prototype.slice.call();

Js code

Array.prototype.slice.call({  
 0:"likeke",  
 1:12,  
 2:true,  
 length:3  
});  
//["likeke", 12, true]

Use [].slice.call(), learn about js Everyone in the prototype chain knows that this method is actually the same as the first method, but the first method above is relatively more efficient.

Js code

[].slice.call({  
 0:"likeke",  
 1:12,  
 2:true,  
 length:3  
});  
//["likeke", 12, true]

Use the Array.from method in ES6;

Js code

Array.from({  
 0:"lk",  
 1:12,  
 2:2013,  
 3:"长安大学",  
 length:4  
});  
//["lk", 12, 2013, "长安大学"]


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