美文网首页
6.对象解构

6.对象解构

作者: dptms | 来源:发表于2017-10-27 14:14 被阅读10次

    对象解构

    对象结构能够帮助我们更为简便的提取对象中的属性,对其重命名,以及赋予默认值。

    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' });
    

    相关文章

      网友评论

          本文标题:6.对象解构

          本文链接:https://www.haomeiwen.com/subject/pewrpxtx.html