Methods for converting JavaScript objects into arrays: 1. Through the "[].slice.call(object)" statement; 2. Using the "Array.from(object)" statement, "Array.from()" Methods can convert traversable objects into arrays (including Set and Map data structures).
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
1. What is an array-like object
For example:
let arrayLike = { '0':"z", '1':"y", '2':"k", length:3 };
The essence is that it has the length attribute, which can be obtained in a similar way to obtaining elements of an arrayarrayLike[0], arrayLike[1] element, you can also get the length of the pseudo array through arrayLike.length.
Common pseudo-arrays include the NodeList collection obtained through DOM operations (document.querySelectorAll('p')), and function formal parameters arguments.
2. Conversion method
Method 1: Through [].slice.call(arrayLike)
//获取当前dom的span组成的伪数组 let spanDomArr = document.querySelectorAll('span'); //通过数组的方法forEach遍历spanDomArr let arr = [].slice.call(spanDomArr); //因为spanDomArr是伪数组,不支持数组的forEach,所以需要先转换成数组 arr.forEach(function(span){ console.log(span) });
Method 2: Through Array.from(arrayLike)
//获取当前dom的span组成的伪数组 let spanDomArr = document.querySelectorAll('span'); //通过数组的方法forEach遍历spanDomArr //因为spanDomArr是伪数组,不支持数组的forEach,所以需要先转换成数组 Array.from(spanDomArr).forEach(function(span){ console.log(span) });
1. Function:
1-Can convert array-like objects into arrays;
2-Can convert traversable Convert the object into an array (including ES6's new data structures Set and Map);
2. Practical application:
1-If the current browser does not deploy this method, you can use the Array.prototype.slice method instead
/* * 方法名:objectToArray * 功能介绍:把类似数组的对象、可遍历的对象转换成数组 * 参数:obj-需要转换的对象 */ var objectToArray = function(obj){ return Array.from ? Array.from(obj) : [].slice.call(obj); };
2-If the parameter is an array, an identical array will be returned
Array.from(["z","y","k"]); //打印:["z","y","k"]
3-Objects with only length attributes cannot be passed array.from conversion
4-Array.from second parameter: is used to process each element and put the processed value Return into array.
let arrayLike = { "0" : "z", "1" : "y", "2" : "k", "length":3 }; Array.from(arrayLike,x=>x+'1'); //等同于 Array.from(arrayLike).map(x=>x+'1'); //打印:["z1","y1","k1"]
【Related recommendations: javascript learning tutorial】
The above is the detailed content of How to convert object to array in javascript. For more information, please follow other related articles on the PHP Chinese website!