J

JS 中的展开运算符、剩余运算符和解构

2025-06-07

JS 中的展开运算符、剩余运算符和解构

大家好,

这是我的第一篇博客。在这篇博客中,我将讨论JavaScript 中的展开运算符、剩余运算符解构。由于我从事 JavaScript 工作已有一年,我以前一直认为展开运算符是用于解构的。最近在做一个项目时,我发现解构的概念完全不同,于是就想在这里分享一下。那么,开始吧。

扩展运算符

扩展运算符用于拆分数组元素或对象属性。它会对数组元素或对象进行深度克隆,因此不会影响原始值。
我们先来看一个数组示例:

const arr1 = [1, 2, 3]
const arr2 = [...arr1, 4, 5]
console.log(arr1);              // [1, 2, 3]
console.log(arr2);              // [1, 2, 3, 4, 5]
arr1.push(6, 7);
console.log(arr1);              // [1, 2, 3, 6, 7]
console.log(arr2);              // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

您可以在上图中看到,在向arr1添加更多值后, arr2并没有发生变化 但是,如果我没有在arr2中提供“...”运算符,情况会怎样呢?让我们在下面找出答案——

const arr1 = [1, 2, 3]
const arr2 = [arr1, 4, 5]
console.log(arr1);              // [1, 2, 3]
console.log(arr2);              // [[1, 2, 3], 4, 5]
Enter fullscreen mode Exit fullscreen mode

是的。它会创建一个嵌套数组。

物体也是如此。

const obj1 = {
  name: "Prince",
  Sex: "Male"
}
console.log(obj1);        //{name: "Prince", sex: "male"}

const obj2 = {
  ...obj1,
age: 25              //{age: 25, name: "Prince", sex: "male}
}
console.log(obj2);

obj1["height"] = "5'8 ft";
console.log(obj1);//{height: "5'8 ft",name: "Prince", sex: "male"}
console.log(obj2);   //{age: 25, name: "Prince", sex: "male}
Enter fullscreen mode Exit fullscreen mode

休息操作员

当函数需要多个参数时,就会使用 Rest 运算符。

const filter = (...args) => {
  return args.filter(val => val%5===0)
}

console.log(filter(5, 10, 2, 4, 20));    // [5, 10, 20]
Enter fullscreen mode Exit fullscreen mode

您可以在上面看到,我们在调用过滤函数时传递了 5 个参数,并且它根据条件打印值,甚至我们可以传递n 个参数,它也能正常工作。

解构

这也是下一代 JavaScript 特性。解构可以轻松地提取数组元素或对象属性,并将它们存储在变量中。
根据上面的定义,你可能会认为它与展开运算符完全相同,但实际上它的工作方式有所不同。
让我们在下面一探究竟。

// Array
const num = [11, 22, 33];
[x, y] = num;
console.log(x);                             // 11
console.log(y);                              // 22
[x, , y] = num;
console.log(x);                             // 11
console.log(y);                             // 33
Enter fullscreen mode Exit fullscreen mode

解构数组时,它会根据左键索引返回索引值。没错,在左侧写入 [x,y] 这样的值并没有创建任何数组。我知道这看起来很奇怪,但就连我之前也感到困惑。

// Object
{name} = {
    name: "Audi",
    model: "A8",
    price: "1.5 cr"
}

console.log(name);                          // "Audi"
console.log(age);                           // undefined
// Above output will be undefined as age is not destructured and aligned with the same key
Enter fullscreen mode Exit fullscreen mode

您可以在上面看到 age 返回未定义,因为它没有被解构并且没有与相同的键对齐。

各位,这篇文章就到这里。🙏感谢阅读!

文章来源:https://dev.to/thekrprince/spread-operator-rest-operator-destructuring-in-js-4nbg
PREV
我的全栈 Web 开发人员资源简介全栈前端后端结束语
NEXT
JavaScript 中的弱记忆