
解构赋值是 es6 中引入的一种语法糖,它允许您将数组或对象中的值解压到变量中。它可以显着简化您的代码并使其更具可读性。
解构数组
基本示例:
const numbers = [1, 2, 3, 4]; const [first, second, ...rest] = numbers; console.log(first); // output: 1 console.log(second); // output: 2 console.log(rest); // output: [3, 4]
- 跳过元素:您可以使用逗号跳过元素:
const [first, , third] = numbers; console.log(first, third); // output: 1 3
- 嵌套数组: 解构可以应用于嵌套数组:
const nestedarray = [[1, 2], [3, 4]]; const [[a, b], [c, d]] = nestedarray; console.log(a, b, c, d); // output: 1 2 3 4
解构对象
基本示例:
const person = { name: 'alice', age: 30, city: 'new york' };
const { name, age, city } = person;
console.log(name, age, city); // output: alice 30 new york
- 重命名属性:您可以在解构期间重命名属性:
const { name: firstname, age, city } = person;
console.log(firstname, age, city); // output: alice 30 new york
- 默认值: 为可能缺少的属性提供默认值:
const { name, age = 25, city } = person;
console.log(name, age, city); // output: alice 30 new york
- 嵌套对象:解构嵌套对象:
const person = { name: 'alice', address: { street: '123 main st', city: 'new york' } };
const { name, address: { street, city } } = person;
console.log(name, street, city); // output: alice 123 main st new york
交换变量
解构可以用来简洁地交换变量:
918 天蓝型企业展示系统旨为打造一个最简单漂亮大方的网站,主打展示型。该程序前台页面结构比较简单,但页面美观十分值得赞赏。前台栏目有:首 页、公司简介、服务项目、工程案例、新闻中心、联系我们。网站以天蓝色系为主,flash也很具特色,底部加入了漂亮大气的百度搜索框模块。前台页面结构简洁明了又别树一帜。 网站后台的栏目分为:系统基本信息 信息管理 产品系统 系统插件 系统管理。 后台除了这
let a = 10; let b = 20; [a, b] = [b, a]; console.log(a, b); // output: 20 10
解构函数参数
您可以解构函数参数以使其更具可读性:
function greet({ name, age }) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
greet({ name: 'Alice', age: 30 });
通过有效地使用解构赋值,您可以编写更干净、更简洁、更易读的 javascript 代码。









