一、解构的定义
JavaScript 对象是由键值对组成的无序集合,在许多场景下需要从中获取某些值。对象解构是从对象中提取出其中一些值,使得它们可以被保存在变量中。
对象解构是在 ES6 中引入的一项新功能,它提供了一种简洁易懂的语法来从对象中获取值。
// 定义一个对象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 从对象中获取值
const { firstName, lastName } = person;
console.log(firstName); // 输出:John
console.log(lastName); // 输出:Doe
二、基本使用
在使用对象解构时,需要定义一个新的变量,再通过对象解构的语法来从原对象中提取出我们需要的值。
对象解构使用花括号{}表示,用于指定从哪个对象中提取哪些属性,然后将其存储到一个变量中。
// 定义一个对象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 从对象中获取值
const { firstName, lastName, age, city } = person;
console.log(firstName); // 输出:John
console.log(lastName); // 输出:Doe
console.log(age); // 输出:30
console.log(city); // 输出:New York
三、重命名
有时候,从对象中提取出来的属性名并不符合我们的变量命名规范,此时我们可以使用冒号:对新变量进行命名。
// 定义一个对象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 从对象中获取值,并进行重命名
const { firstName: fName, lastName: lName } = person;
console.log(fName); // 输出:John
console.log(lName); // 输出:Doe
四、默认值
从对象中提取值时,如果属性值不存在,则会赋予变量 undefined 值,但我们可以给对象解构中的变量设置默认值。
// 定义一个对象
const person = {
firstName: 'John',
lastName: 'Doe'
};
// 从对象中获取值,并设置默认值
const { firstName = 'Jane', lastName = 'Doe', age = 30 } = person;
console.log(firstName); // 输出:John
console.log(lastName); // 输出:Doe
console.log(age); // 输出:30
五、函数参数
对象解构同样可以用于函数参数传递中,从而简化代码。
// 定义一个对象
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
// 定义一个函数,使用对象解构作为参数
function displayPerson({ firstName, lastName, age, city }) {
console.log(`Name: ${firstName} ${lastName}`);
console.log(`Age: ${age}`);
console.log(`City: ${city}`);
}
// 调用函数
displayPerson(person);
六、嵌套对象
如果对象中的属性也是一个对象,我们同样可以使用对象解构来方便的获取内部对象的属性。
// 定义一个对象
const person = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
zipcode: '10001'
},
hobbies: ['music', 'movies', 'sports']
};
// 从嵌套对象中获取值
const { name, address: { street, city, zipcode }, hobbies } = person;
console.log(name); // 输出:John Doe
console.log(street); // 输出:123 Main St
console.log(city); // 输出:New York
console.log(zipcode); // 输出:10001
console.log(hobbies); // 输出:['music', 'movies', 'sports']
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/246836.html