JavaScript 扩展运算符

x33g5p2x  于2022-05-05 转载在 Java  
字(1.9k)|赞(0)|评价(0)|浏览(398)

在本教程中,您将借助示例了解 JavaScript 扩展运算符。
    扩展运算符是JavaScript ES6版本中新增的可用功能。

扩展运算符

扩展运算符…用于扩展可迭代类型或数组。例如,

const arrValue = ['My', 'name', 'is', 'Jack'];

console.log(arrValue);   // ["My", "name", "is", "Jack"]
console.log(...arrValue); // My name is Jack

在这种情况下,代码:

console.log(...arrValue)

相当于:

console.log('My', 'name', 'is', 'Jack');
使用扩展运算符复制数组

您还可以使用扩展语法 …将项目复制到单个数组中。例如,

const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];

console.log(arr2); 
//  Output:
//  ["one", "two", "three", "four", "five"]
使用扩展运算符克隆数组

在 JavaScript 中,对象是通过引用而不是通过值来分配的。例如,

let arr1 = [ 1, 2, 3];
let arr2 = arr1;

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

// append an item to the array
arr1.push(4);

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

在这里,两个变量 arr1 和 arr2 指的是同一个数组。因此,一个变量的变化会导致两个变量的变化。
    但是,如果要复制数组以使它们不引用同一个数组,则可以使用扩展运算符。这样,一个数组中的变化不会反映在另一个数组中。例如,

let arr1 = [ 1, 2, 3];

// copy using spread syntax
let arr2 = [...arr1];

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

// append an item to the array
arr1.push(4);

console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3]
带对象的扩展运算符

您还可以将扩展运算符与对象文字一起使用。例如,

const obj1 = { x : 1, y : 2 };
const obj2 = { z : 3 };

// add members obj1 and obj2  to obj3
const obj3 = {...obj1, ...obj2};

console.log(obj3); // {x: 1, y: 2, z: 3}

这里,使用扩展运算符将 obj1 和 obj2 属性添加到 obj3。

剩余参数

当扩展运算符用作参数时,它被称为剩余参数。
    您还可以使用剩余参数在函数调用中接受多个参数。例如,

let func = function(...args) {
    console.log(args);
}

func(3); // [3]
func(4, 5, 6); // [4, 5, 6]

这里,

  • 当将单个参数传递给func()函数时,剩余参数仅采用一个参数。
  • 当传递三个参数时,剩余参数采用所有三个参数。

注意:使用剩余参数会将参数作为数组元素传递。
    您还可以使用扩展运算符将多个参数传递给函数。例如,

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

const num1 = [1, 3, 4, 5];

sum(...num1); // 8

如果使用扩展运算符传递多个参数,该函数将接受所需的参数,并忽略剩余参数。
    注:ES6中引入了扩展运算符。有些浏览器可能不支持使用扩展语法。访问JavaScript Spread Operator support了解更多信息。

上一教程 :JS Template Literals                                          下一教程 :JS Map

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/spread-operator

相关文章

微信公众号

最新文章

更多