在 ECMAScript(即 JavaScript)中,解构赋值是一种方便的语法,允许我们将数组或对象的属性值提取到单独的变量中。解构赋值可以使代码更简洁、易读。
const arr = [1, 2, 3];
const [first, second, third] = arr;
console.log(first); // 输出 1
console.log(second); // 输出 2
console.log(third); // 输出 3
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
const { name, age, city } = obj;
console.log(name); // 输出 'John'
console.log(age); // 输出 30
console.log(city); // 输出 'New York'
const arr = [1, 2];
const [first, second, third = 3] = arr;
console.log(first); // 输出 1
console.log(second); // 输出 2
console.log(third); // 输出 3
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 输出 2
console.log(b); // 输出 1
function sum({ x, y }) {
return x + y;
}
const result = sum({ x: 1, y: 2 });
console.log(result); // 输出 3
解构赋值在实际编程中非常有用,可以大大提高代码的可读性和简洁性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。