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
Post a Comment