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

js multiple methods to convert pseudo array to standard array

巴扎黑
巴扎黑Original
2016-11-25 10:17:041197browse

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 objects 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 to 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() Anyone who knows the js 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:"Chang'an University",

length:4

});

//["lk", 12, 2013, "Chang'an University"]


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