ES6数组的扩展--扩展运算符

 1.扩展运算符

扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

{

console.log(...[1, 3, 2, 43]);//1,3,2,43

console.log(1, 2, ...[2, 5, 4], 9);//1,2,2,5,4,9

let div = document.querySelectorAll('div');

console.log(...div)

}

 该运算符主要用于函数调用

{

function push(array, ...items) {
array.push(...items);

}
function add(x, y) {
return x + y;
}
const numbers = [4, 38];
console.log(add(...numbers)) // 42

}

 上面代码中,array.push(...items)和add(...numbers)这两行,都是函数的调用,它们的都使用了扩展运算符。该运算符将一个数组,变为参数序列。

 扩展运算符与正常的函数参数可以结合使用,非常灵活。

{

function f(v, w, x, y, z) { }

const args = [0, 1];

f(-1, ...args, 2, ...[3]);

}

 扩展运算符后面还可以放置表达式。

{

let x = 2;

let arrrA = [2, 3, 4]

let arr = [...([x > 0 ? [...arrrA] : []]), 23]

console.log(arr)

}

 如果扩展运算符后面是一个空数组,则不产生任何效果。

{

// (...[1,2])

// Uncaught SyntaxError: Unexpected number

// console.log((...[1,2]))

// Uncaught SyntaxError: Unexpected number

}

 上面两种情况都会报错,因为扩展运算符所在的括号不是函数调用,而console.log(...[1, 2])就不会报错,因为这时是函数调用。

 2.替代函数的 apply 方法

 由于扩展运算符可以展开数组,所以不再需要apply方法,将数组转为函数的参数了。

{

function add(x, y, j) {

return x + y + j;

}

// es5

console.log(add.apply(null, [1, 2, 3]));

// es6

console.log(add(...[1, 2, 3]));

}

 下面是扩展运算符取代apply方法的一个实际的例子,应用Math.max方法,简化求出一个数组最大元素的写法。

{

// es5

console.log(Math.max.apply(null, [1, 2, 43, 2, 3, 212]));

// es6

console.log(Math.max(...[1, 2, 43, 2, 3, 212, 56]))

// 等同于

Math.max(14, 3, 77);

}

 另一个例子是通过push函数,将一个数组添加到另一个数组的尾部

{

let arr1 = [1, 2, 32, 1, 2, 4],

arr2 = [5, 3, 6, 4, 2, 4];

// es5

Array.prototype.push.apply(arr1, arr2);

console.log(arr1)

// es6

arr1.push(...arr2)

console.log(arr1)

}

 3.扩展运算符的应用

(1)复制数组

 数组是复合的数据类型,直接复制的话,只是复制了指向底层数据结构的指针,而不是克隆一个全新的数组。

{

let arr1 = [1, 2],

arr2 = [];

arr2 = arr1;

console.log(arr2);//[1,2]

arr1[0] = 2;

console.log(arr2) //[2,2]

}

 ES5 只能用变通方法来复制数组

{

let arr1 = [1, 2],

arr2 = [];

let a1 = [1, 2];

let a2 = a1.concat();

a2[0] = 2;

a1 // [1, 2]

}

 上面代码中,a1会返回原数组的克隆,再修改a2就不会对a1产生影响。

{

let a1 = [1, 2];

// 写法一

let a2 = [...a1];

// 写法二

 let [...a2] = a1;

}

上面的两种写法,a2都是a1的克隆

 (2)数组的合并

 扩展运算符提供了数组合并的新写法。

{

let arr1 = ['a', 'b'];

let arr2 = ['c'];

let arr3 = ['d', 'e'];

// ES5 的合并数组

arr1.concat(arr2, arr3);

// [ 'a', 'b', 'c', 'd', 'e' ]



// ES6 的合并数组

[...arr1, ...arr2, ...arr3]

// [ 'a', 'b', 'c', 'd', 'e' ]

}

// 不过,这两种方法都是浅拷贝,使用的时候需要注意。

{

let a1 = [{ foo: 1 }];

let a2 = [{ bar: 2 }];



let a3 = a1.concat(a2);

let a4 = [...a1, ...a2];



a3[0] === a1[0] // true

a4[0] === a1[0] // true

}

 上面代码中,a3和a4是用两种不同方法合并而成的新数组,但是它们的成员都是对原数组成员的引用,这就是浅拷贝。如果修改了原数组的成员,会同步反映到新数组。

 (3)与解构赋值结合

 扩展运算符可以与解构赋值结合起来,用于生成数组。

{

let res = ['b', 'c'], a = ['a'], list = [];

// ES5

a = list[0], rest = list.slice(1);

console.log(list);

// ES6

[a, ...rest] = list;

[...list] = [a, res]

console.log(list);

}
{

const [first1, ...rest1] = [1, 2, 3, 4, 5];

first1 // 1

rest1 // [2, 3, 4, 5]



const [first2, ...rest2] = [];

first2 // undefined

rest2 // []



const [first3, ...rest3] = ["foo"];

first3 // "foo"

rest3 // []

}

 如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。

{

// const [...butLast, last] = [1, 2, 3, 4, 5];

// 报错

// const [first, ...middle, last] = [1, 2, 3, 4, 5];

// 报错

}

 (4)字符串

 扩展运算符还可以将字符串转为真正的数组。

{

console.log([...'hello']);

// [ "h", "e", "l", "l", "o" ]

}

{

let str = 'x\uD83D\uDE80y';

str.split('').reverse().join('');

// 'y\uDE80\uD83Dx'

[...str].reverse().join('');

console.log(str)

// 'y\uD83D\uDE80x'

}

 上面代码中,如果不用扩展运算符,字符串的reverse操作就不正确。

 4.实现了 Iterator 接口的对象

 任何 Iterator 接口的对象(参阅 Iterator 一章),都可以用扩展运算符转为真正的数组。

{

let nodelist = document.querySelectorAll('div');

console.log(nodelist);

console.log(...nodelist);

console.log([...nodelist]);

}

 上面代码中,querySelectorAll方法返回的是一个NodeList对象。它不是数组,而是一个类似数组的对象。这时,

 扩展运算符可以将其转为真正的数组,原因就在于NodeList对象实现了 Iterator

{

let arrayLike = {

'0': 'a',

'1': 'b',

'2': 'c',

length: 3

};

// TypeError: Cannot spread non-iterable object.

// let arr = [...arrayLike];

let arr = Array.from(arrayLike);

console.log(arr);

}

 上面代码中,arrayLike是一个类似数组的对象,但是没有部署 Iterator 接口,扩展运算符就会报错。这时,可以改为使用Array.from方法将arrayLike转为真正的数组。

(6)Map 和 Set 结构,Generator 函数

// 扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 结构。

猜你喜欢

转载自blog.csdn.net/dwb123456123456/article/details/84790158