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

What is the difference between the box-size property content-box and border-box in the css box model?

 The box model is a very important concept in CSS layout, it includes content area, padding, border, and margin. Box models can be divided into two types: standard box models and IE box models. The box model, as the name suggests, is used to hold things, and the things it holds are the content of HTML elements. In other words, every visible HTML element is a box.

Js uses recursive way to traverse the dom tree to dynamically create element nodes

 What is a dom tree? In short, DOM is the Document Object Model, which provides a structured representation for documents and defines how to access the document structure through scripts. DOM is composed of nodes. After the HTML is loaded, the rendering engine will generate a DOM tree in memory based on the HTML document. This article uses a small case to traverse the dom tree recursively. The core of the method is to determine whether the incoming data is an array, and then traverse the root node. Note that there must be an end condition when using recursion.