spread operator...
Spread operator ...
converts an array to a comma-separated sequence of arguments
...
Can be followed by an expression that returns an array...
If the latter is an empty array, it will have no effect
let m = 2,
arr = [...(m > 1 ? [1, 2] : [3, 4])];
function fn(a, b, c) {
return a + b + c;
}
console.log(fn(5, ...arr)); // 8
application
Alternative to appplay
// 求数组最大值
// ES5
Math.max.apply(null, [5, 3, 7]);
// ES6
Math.max(...[5, 3, 7])
copy array
make a full copy, not a reference to the array
let arr = [3, 2, 5];
/* ES5 */
let a = arr.concat();
/* ES6 */
// 写法一
let b = [...arr];
// 写法二
let [...c] = arr;
console.log(a);
console.log(b);
console.log(c);
Merge arrays
let a = [1, 2],
b = [3],
c = [4, 5];
// ES5
let m = a.concat(b, c);
// ES6
let n = [...a, ...b, ...c];
console.log(m);
console.log(n);
Combined with destructuring assignment
If the spread operator is used for assignment, it can only be placed at the end, otherwise an error will be reported
let [a,...b] = [1,2,3];
console.log(a); // 1
console.log(b); // [2,3]
// let [...b,a] = [1,2,3]; // 报错
let [m,...n] = [];
console.log(m); // undefined
console.log(n); // []
Convert an object with Iterator interface to an array
let a = [...'hello'];
console.log(a); // ["h", "e", "l", "l", "o"]
// querySelectorAll 方法返回的是 nodeList 对象,这个对象是类数组而不是真的数组,扩展运算符可将它转换为数组
let dvs = document.querySelectorAll('div'),
arr = [...dvs];
find,findIndex
find(fn,this), this is optional, it is the this of fn, execute fn on each item of the array until the first item whose return value is true is found, and return the item, if no matching condition is found item returns undefined
findIndex is similar to find, returns the position of the first item that matches the condition, and returns -1 if none of the items match
fill
Array.from(a,fn)
- Any object with a length property can be converted to an array by Array.from(), such as nodeList, arguments
- a is a true array, returns an identical new array
Array.of()
Array.of() can receive multiple parameters, which are used as array members to generate an array
copyWithin()
Receives three parameters, overlays the members at the specified position of the array with the members at another position, and returns the array
.
.
.