Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

In the early days of JavaScript, array may be the first collection we come into contact with. More data structures can be simulated through array. With ES6, ES2017 introduces more data structure types such as Map, Set or WeakMap

We know that arrays can be created in a variety of ways, from simple literals to constructors using the new keyword.

const arr1 = [1.2.3]
Copy the code

Array.of

When we create an Array using the Array constructor, if we just pass in a number, that number is used to create an Array of length 1. Instead, we create an empty Array of length 3, which may create empty slots. To solve this problem, ES6 introduces a new API for creating arrays array.of (…)

Array.from

A variety of methods to create arrays using array. from

We can create an array based on strings,

const aString = "machinelearning";
const arr6 = [...aString];
console.log(arr6);//[ 'm', 'a', 'c', 'h', 'i', 'n', 'e', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g' ]

Copy the code
const arr7 = Array.from(aString);
console.log(arr7)//[ 'm', 'a', 'c', 'h', 'i', 'n', 'e', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g' ]
Copy the code

A set of combined operations

Here you can manipulate an array using pipe

var arr2 = (Array.from({length:5}).fill(1).map((v,i) = >i))
console.log(arr2)//[0, 1, 2, 3, 4]
Copy the code
var arr3 = [1.1.2.3.5]
var uniquedArr3 = Array.from(new Set(arr3));
console.log(uniquedArr3)//[1, 2, 3, 5]
Copy the code

Convert arguments to an array

function fn1(){
    console.log(Array.from(arguments))}Copy the code

Avoid empty slot arrays

var emptySlotsArr = [];
emptySlotsArr.length=4;
emptySlotsArr[2] ='foo'
console.log(emptySlotsArr)//[ <2 empty items>, 'foo', <1 empty item> ]

const a = Array.from(emptySlotsArr);
console.log(a)//[ undefined, undefined, 'foo', undefined ]

Copy the code

mapping

Create an empty Array with a literal, then set the Array to 4 empty slots with the length property, and pass this empty slot to array. from can be used to fill empty slots. Using array. from solves this problem in just one step.

var b = Array(3)
console.log(b)//[ <3 empty items> ]
var c = Array.apply(null, {length:3})
console.log(c)//[ undefined, undefined, undefined ]
console.log(Array.from({length:3}))//[ undefined, undefined, undefined ]
Copy the code

Create arrays and subtypes

We have discussed array.of (..). And Array. The from (..) Both create a new array in a similar way to the constructor.

class MyArray extends Array {}console.log(MyArray.from([1.2]) instanceof MyArray) //true
console.log(Array.from(MyArray.from([1.2])) instanceof MyArray)//false
Copy the code

of(..) And from (..) Both use access constructors to construct arrays, if the base array.of (..) class is used. If myarry.of (..) is used, then the Array instance is obtained. That’s an instance of MyArry