6.对象解构
2017-10-27 本文已影响10人
dptms
对象解构
对象结构能够帮助我们更为简便的提取对象中的属性,对其重命名,以及赋予默认值。
const Tom = {
name: 'Tom jones',
age: 25,
family: {
mother: 'Norah Jones',
father: 'Rachard Jones',
brother: 'Howard Jones',
}
}
const father = 'Dad';
const { name, age } = Tom;
const { mother, father: f, brother: b, sister = 'Marry' } = Tom.family;
console.log(name); // Tom jones
console.log(f); // Howard jones
console.log(father); // Dad
// console.log(brother); // brother is not defined
console.log(sister); // Marry
默认设置小例子
function appendChildDiv(options = {}) {
const {
parent = 'body',
width = '100px',
height = '80px',
backgroundColor = 'green',
} = options;
const div = document.createElement('div');
div.style.width = width;
div.style.height = height;
div.style.backgroundColor = backgroundColor;
document.querySelector(parent).appendChild(div);
}
appendChildDiv({ width: '200px', height: '300px', backgroundColor: 'red' });