码迷,mamicode.com
首页 > 其他好文 > 详细

[ES6] 08. Destructuring Assignment -- 1

时间:2014-11-21 01:31:07      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   os   sp   for   

Here is the way you get value from an object:

var obj = {
    color: "blue"
}
console.log(obj.color);  //blue

 

Destructuring Assignment:


 

Object

Destructuring Assignment is somehow different: 

var {color} = {
    color: "green"
}
console.log(color); //green

It tells to looking for color property, so I get "green".

 

If I have muli pros (color, name, position, state): And I want to get color, and position properties.

var {color, position} = {
    color: "green",
    name: "Great",
    position: "Finland",
    state: "Who knows"
}
console.log(color); //green
console.log(position); //Finland

 

Function

If I have a fn which return an object: And from the object, I just want name and state.

function getObj(){
    return{
        color: "green",
        name: "Great",
        position: "Finland",
        state: "Who knows"
    };
}

var {name, state} = getObj();
console.log(name); //Great
console.log(state); //Who knows

 

From the example, if you want to name something else:

{name: who, state: where} 
function getObj(){
    return{
        color: "green",
        name: "Great",
        position: "Finland",
        state: "Who knows"
    };
}

var {name: who, state: where} = getObj();
console.log(who); //Great
console.log(where); //Who knows

 

Array

If I have an array, from which I just want the first and the third element from the array:

var [first,,third] = [‘first‘, ‘second‘, ‘third‘, ‘forth‘];
console.log(first);  //first
console.log(third);  //third

 

If I want to forEach of array: and get the firstName

var people = [
    {
        firstName: "Allen",
        secondName: "Hook",
        email: "allen@abc.com"
    },
    {
        firstName: "Anton",
        secondName: "Tee",
        email: "tee@abc.com"
    },
    {
        firstName: "Yui",
        secondName: "Gegg",
        email: "gegg@abc.com"
    }
];

people.forEach(({firstName}) => console.log(firstName));

/*
 Allen
 Anton
 Yui
 * */

 

 

or:

var [, secondPerson] = people;
function logEmail({email}){
    console.log(email);
}
logEmail(secondPerson); //tee@abc.com

 

[ES6] 08. Destructuring Assignment -- 1

标签:des   style   blog   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/Answer1215/p/4111895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!