扩展运算符
扩展运算符…用于扩展可迭代类型或数组。例如,
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]
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
上一教程 :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
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/216674.html原文链接:https://javaforall.net
