*它可与数组和对象一起使用,在数组中,它的使用时间为:
1。 构建数组
2. 将参数传递给函数
1- 构建数组:
const arr = [5, 6, 7]; // without the spread operator ? const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]]; console.log(badArr); // [1, 2, 3, 4, 5, 6, 7] // with the spread operator ? const goodArr = [1, 2, 3, 4, ...arr]; console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]
如您所见,扩展运算符使事情变得更加容易。
如果您再次想要扩展数组的各个元素,请使用扩展运算符:
console.log(...goodArr); // 1 2 3 4 5 6 7 //the line above is just like writing this code: console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
const foods = ['chicken', 'meat', 'rice']; const Newfoods = [...foods, 'pizza ']; console.log(Newfoods); // ['chicken', 'meat', 'rice', 'pizza ']
console.log(foods); // ['chicken', 'meat', 'rice']
扩展运算符与数组的两个有用用例:
1.创建数组的副本:
const arrOriginal = [1, 2, 3, 4, 5]; const arrCopy = [...arrOriginal]; console.log(arrCopy); // [1, 2, 3, 4, 5]
2.合并两个或多个数组:
const arr1 = ['A', 'B', 'C']; const arr2 = ['D', 'E', 'F']; const mergedArr = [...arr1, ...arr2]; console.log(mergedArr); // ['A', 'B', 'C', 'D', 'E', 'F']
const str = 'spongeBob'; const letters = [...str, 'squarePants']; console.log(letters); // ['s', 'p', 'o', 'n', 'g', 'e', 'B', 'o', 'b', 'squarePants']
console.log(`spelling sponge bob's name: ${...str}`); // Expression expected
2- 将参数传递给函数
const arr = [5, 6, 7]; // without the spread operator ? const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]]; console.log(badArr); // [1, 2, 3, 4, 5, 6, 7] // with the spread operator ? const goodArr = [1, 2, 3, 4, ...arr]; console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]
console.log(...goodArr); // 1 2 3 4 5 6 7 //the line above is just like writing this code: console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
希望您能理解这里的所有内容,如果您有任何疑问,请随时在评论部分提问,感谢您的阅读?
以上是JavaScript 扩展运算符的详细内容。更多信息请关注PHP中文网其他相关文章!