New feature of ES6 | array extension

1. Extension operator

(1) Basic usage

  • Array to parameter sequence (comma separated)
let arr = [1,2,3];

console.log(...arr);  // 1 2 3
  • function call
let arr = [1,2];

function add(x,y) {
    console.log(x+y);
};

add(...arr);  // 3
  • Extension operators can place expressions
const arr = [
    ...(x>0 ? ['a']:[]),
    'b',
]
  • If the extension operator is followed by an empty array, it has no effect

(2) apply method instead of array

Since the extension operator can expand the array, there is no need to use the apply method to turn the array into a function parameter

function fn(x, y, z) {
    console.log(x, y, z);
};

let args = [1,2,3];

// ES5 writing method
fn.apply(null, args);  // 1 2 3

// ES6 writing method
fn(...args);  // 1 2 3
  • Simplify to find the largest element of an array
let args = [1,2,3,4,5];

// ES5 writing method
console.log(Math.max.apply(null,args))  // 5


// ES6 writing method
console.log(Math.max(...args));   // 5
  • Add an array to the tail of another array through the push function
let arr1 = [1,2,3];
let arr2 = [4,5,6];

// ES5 writing method
Array.prototype.push.apply(arr1,arr2)
console.log(arr1);    // [ 1, 2, 3, 4, 5, 6 ]

// ES6 writing method
arr1.push(...arr2);
console.log(arr1);   // [ 1, 2, 3, 4, 5, 6 ]

console.log([...arr1, ...arr2]);   // [ 1, 2, 3, 4, 5, 6 ]

(3) Application of extension operator

  • Merge array
let arr1 = [1,2,3];
let arr2 = [4,5,6];

console.log([...arr1, ...arr2]);   // [ 1, 2, 3, 4, 5, 6 ]
  • Combined with deconstruction assignment
let arr = 'abc,def';

let [x,y] = arr.split(',');

console.log([x,...y]);  // [ 'abc', 'd', 'e', 'f' ]

If the extension operator is used for array assignment, it can only be placed in the last bit of the parameter, otherwise an error will be reported

  • Return value of function
let dateFields =  readDateFields(database);
let d = new Date(...dateFields);
  • character string
console.log([...'Katrina'])  // ['K', 'a', 't','r', 'i', 'n','a']
  • An object that implements the Iterator interface

Any object of the Iterator interface can be converted into a real array with the extension operator
In ES6, there are three types of array structures with Iterator interface: array, some array like objects, Set and Map structures

  • Map and Set structure, Generator function
let m = new Map([
    [1,'one'],
    [2,'two'],
    [3,'three'],
]);


console.log([...m]);   // [ [ 1, 'one' ], [ 2, 'two' ], [ 3, 'three' ] ]

2. Array related

(1)Array.from()

Array. The from () method is used to convert two types of objects into real arrays: array like objects and iteratable objects (including the new data structures Set and Map in ES6)

let arrayLike = {
    '0':'a',
    '1':'b',
    '2':'c',
    length:3,
};

// ES5 writing method
let arr1 = [].slice.call(arrayLike);
console.log(arr1);   // [ 'a', 'b', 'c' ]

// ES6 writing method
let arr2 = Array.from(arrayLike);
console.log(arr2);  // [ 'a', 'b', 'c' ]
  • Array.from accepts the second parameter and can specify a callback function, which is similar to the map method of array. It is used to process each element and put the processed value into the returned array
let arr = [1,2,3];

let arr1 = Array.from(arr, item => item*2);

console.log(arr1);  // [ 2, 4, 6 ]
  • Can be used to generate a continuous array of specified start and end
let start = 2, end = 6;
console.log(Array.from(new Array(end+1).keys()).slice(start));   // [ 2, 3, 4, 5, 6 ]
  • Array de duplication
let arr = [1,2,1,3];
let newArray = Array.from(new Set(arr));
console.log(newArray);   // [ 1, 2, 3 ]

(2)Array.of()

Used to convert a set of values into an array

Array.of(1,2,3) // [1,2,3]

Array.of() is mainly used to make up for the deficiency of Array(). Let's look at the following:

Array() // [];
Array(3) // [ , , ];
Array(3, 2, 1) // [3,2,1];

It is not difficult to see that when the Array method has no parameters, one parameter or three parameters, the returned results are different. Only when the number of parameters is not less than 2, the Array() will return a new Array composed of parameters
So, array Of () can basically be used to replace Array() or new Array(), and there is no overload caused by different parameters
Array. The behavior of () can be realized by the following code:

function ArrayOf() {
	return [].slice.call(arguments);
}

(3)copyWithin()

The copyWithin() method copies the members of the specified position to other positions within the current array (overwriting the original members), and then returns the current array

The syntax is:

Array.prototype.copyWithin(target, start=0, end=this.length);
  • target (required): replace data from this location
  • start (optional): read data from this position. The default value is 0. If it is negative, it means the reciprocal
  • end (optional): stop reading data before reaching this position. By default, it is equal to the length of the array. If it is a negative value, it indicates the reciprocal
let arr = [1,2,3,4,5,6,7,8];

console.log(arr.copyWithin(1,3,5));    // [1, 4, 5, 4,5, 6, 7, 8 ]

(4)Array.find() && Array.findIndex()

The find method is used to find the first qualified array member. If it is not found, it returns undefined
The findIndex method is used to find the index of the first qualified array member. If it is not found, it returns - 1

let arr = [1,2,3,4,5,6,7,8];

console.log(arr.find(item => item > 5));   // 6

console.log(arr.findIndex(item => item > 5));   // 5

(5)Array.fill()

fill fills an array with the given value
Used to initialize an empty array

let arr = [1,2,3,4,5,6,7,8];

console.log(arr.fill(10));   // [10, 10, 10, 10, 10, 10, 10, 10]

(6)Array.entries() Array.keys() Array.values()

Traversal using for of
Array.entries key value pair
Array.keys and array Values are the key name and key value respectively

(7)Array.includes()

Arrray.includes returns a Boolean value, which is used to determine whether the array contains the given value, similar to the inclusion of a string
The second parameter can be passed in to specify the starting position of the search. The default is 0. If the second parameter is negative, it indicates the position of the reciprocal. If it is greater than the length of the array, it is reset to 0

let arr = [1,2,3,4,5,6,7,8];

console.log(arr.includes(3, 5)); // false because 3 does not appear after the search location
  • includes solves the disadvantages of indexOf:
    (1) It is not semantic enough. Its meaning is to find the first occurrence position of the parameter value, so it is necessary to compare whether it is not equal to - 1
    (2) It internally uses the strict equality operator (= = =) to judge, which will lead to misjudgment of NaN
[NaN].indexOf(NaN);  // -1

[NaN].includes(NaN); // true
  • includes and set should be distinguished from has in map
    (1) has in map is used to find the key name
    (2) has in set is used to find the value

(8) Empty bit of array

Empty bit of array: there is no value in a certain position of the array

Array(3)  // [ , , ]

In ES5, vacancies are ignored in most cases:

  1. forEach(), filter(), every(), some() will skip empty bits
  2. map() skips the empty bit, but keeps the value
  3. join() and toString() treat empty bits as undefined, while undefined and null are processed into strings
    In ES6, empty spaces are not ignored, but are explicitly changed to undefined
  • Array.from()
  • Extended operator
  • copyWithin() will copy together with the empty bit
  • fill() treats empty bits as normal array positions
  • The for of loop will also traverse the empty bits, but if you change to map traversal, the empty bits will be skipped
    The following methods will be processed as undefined
  • Array.entries()
  • Array.keys()
  • Array.values()
  • Array.find()
  • Array.findIndex()

Keywords: Javascript Front-end TypeScript

Added by helloworld on Fri, 04 Mar 2022 23:01:39 +0200