Skip to main content

JS convert pseudo array to array

In JS, pseudo-arrays are very common, also called array-like. So it is very important to understand and understand good pseudo-arrays. This article will explain in detail what a pseudo-array is and how to convert a pseudo-array into a real array in ES5 and ES6 respectively. What is a pseudo-array? The main characteristic of a pseudo-array: it is an object, and that object has a length property.

Pseudo-array of object type

let obj={
        0:"aaa",
        1:"bbb",
        2:"ccc",
        3:"ddd",
        length:4
       }
//    let arr=[];
//    arr.push.apply(arr,obj);
//    console.log(arr,arr instanceof Array);// ["aaa", "bbb", "ccc", "ddd"] true
Using the Array.from() method in ES6
 let obj={
        0:"aaa",
        1:"bbb",
        2:"ccc",
        3:"ddd",
        length:4
       }
       let b=Array.from(obj);
       console.log(b,b instanceof Array);
Using the Array.prototype.slice.call() method in ES6
 let obj={
        0:"aaa",
        1:"bbb",
        2:"ccc",
        3:"ddd",
        length:4
       }
       let b=Array.prototype.slice.call(obj);
       console.log(b,b instanceof Array);
Strings are converted to arrays using spread operator
let str="hello"
       console.log([...str])//["h", "e", "l", "l", "o"]

Comments

Popular posts from this blog

A simple understanding of ES6 iterators

 What is an iterator?An iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the traversal operation as long as the iterator interface is deployed.ES6 created a new traversal command for...of loop, which natively has a data structure with the iterator interface (which can be traversed with for...of). Contains Array, Arguments, Set, Map, String, TypedArray, NodeList. Of course, you can also implement this interface manually, which is convenient for practical use.