Extensions of ES6 arrays–Array.from() and Array.of()

Time:2022-9-18

1. Array.from() : Convert a pseudo-array object or traversable object to a true array

1. What is a pseudo-array

If all keys of an object are positive integers or zero and have a length property, then this object is very similar to an array, which is grammatically called an "array-like object", which is a pseudo-array.

var obj = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
obj[0] // 'a'
obj[1] // 'b'
obj.length // 3
obj.push('d') // TypeError: obj.push is not a function

In the above code, the object obj is an array-like object. But "array-like objects" are not arrays, because they don't have array-specific methods. The object obj does not have an array push method, and an error will be reported if this method is used.

2. What are pseudo-arrays?

A typical "array-like object" isThe arguments object for functions, and most sets of DOM elements, as well as strings.

3. How to convert to a true array

①The slice method of an array can turn an "array-like object" into a real array

function doSomething(){
    console.log(arguments)
    var args = Array.prototype.slice.call(arguments);
    args.push("hj")
    console.log(args)
    return args
}
doSomething(1,2,3)

Or you can also write:

function doSomething(){
    var args = [].slice.call(arguments);
    return args
}
doSomething(1,2,3)

Although this method can also achieve the purpose of turning an array-like into an array, it is not intuitive. ES6 added the Array.from() method to provide a clear and clear way to address this need, and the latter approach is recommended.

②Array.from()

Test 1

Test 2

Test 3


let btns = document.getElementsByTagName("button")
console.log("btns",btns);//Get a pseudo array
//btns.forEach(item=>console.log(item)) Uncaught TypeError: btns.forEach is not a function
Array.from(btns).forEach(item=>console.log(item)) converts pseudo-array to array


In ES6, the spread operator (…) can also convert some data structures into arrays. It's just that it needs to call the iterator interface Symbol.iterator behind the scenes. It is worth noting that if an object does not deploy the iterator interface, it is not possible to convert an array-like object into an array using the spread operator.

function doSomething (){ 
  return [...arguments] 
}
doSomething('a','b','c'); // ["a","b","c"]

4.Array.from() usage

Array.from accepts three parameters, but only input is required:

  • input: array-like and iterable objects that you want to convert
  • map: an array-like map method that processes each element and puts the processed value into the returned array
  • context: this used in the binding map

As long as it is a data structure with the iterator interface deployed, Array.from can convert it to an array:

let arr = Array.from('juejin'); 
console.log(arr); //["j", "u", "e", "j", "i", "n"]

Array.from can also accept a second parameter, which is similar to the map method of an array, used to process each element, and put the processed value into the returned array.

Array.from([1, 2, 3], (x) => x * x)// [1, 4, 9]
// Equivalent to
Array.from([1,2,3].map(x => x * x))

If the this keyword is used in the map function, you can also pass in the third parameter of Array.from to bind this.

Array.from() can convert various values ​​to real arrays, and also provides map function. This actually means that as long as you have a primitive data structure, you can first process its values, then convert it into a canonical array structure, and then use a large number of array methods.

Array.from({ length: 2 }, () => 'jack')// ['jack', 'jack']

2. Array.of(v1, v2, v3) : Convert a series of values ​​into an array

When calling the new Array( ) constructor, depending on the type and number of arguments passed in, it actually leads to some different results, for example:

let items = new Array(2) ;
console.log(items.length) ; // 2
console.log(items[0]) ; // undefined
console.log(items[1]) ;
let items = new Array(1, 2) ;
console.log(items.length) ; // 2
console.log(items[0]) ; // 1
console.log(items[1]) ; // 2

When the Array constructor is called with a single numeric parameter, the array's length property is set to that parameter. If called with multiple arguments (numeric or not), those arguments also become the items of the target array. This behavior of arrays is confusing and risky, because sometimes the type of the passed parameter may not be taken care of.

ES6 introduced the Array.of( ) method to solve this problem. This method works very much like an Array constructor, but does not cause special results when using a single numeric parameter.The Array.of( ) method always creates an array of all incoming arguments, regardless of the number and type of arguments

let items = Array.of(1, 2);
console.log(items.length); // 2
console.log(items[0]); // 1
console.log(items[1]); // 2
items = Array.of(2);
console.log(items.length); // 1
console.log(items[0]); // 2

Array.of can basically be used to replace Array() or newArray(), and there is no overload due to different parameters, and their behavior is very uniform.

Recommended Today

linux learning

Linux 1 Overview is an operating system The difference between linux and centos 7 is like the difference between windows and windows 7 On the server side, Linux is very popular in the development world The server uses the command line, and we also learn based on the command line 2. Environment construction 2.1 Download […]