Home > Web Front-end > JS Tutorial > body text

js multiple methods to convert pseudo array to standard array

巴扎黑
Release: 2016-12-06 10:15:05
Original
1448 people have browsed it

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]
Copy after login

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]
Copy after login

Use the Array.from method in ES6;

Js code

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


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!