[ES6] 08. Destructuring Assignment -- 1

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
 * */
复制代码

 

To make it clear:

复制代码
people.foreach(function(person){
    console.log(person.firstName);
});

//Destructuring 
people.foreach(function( {firstName} ){
    console.log(firstName);
});

//Destructuring  + Allow
people.foreach( ( {firstName} ) => console.log(firstName); )
复制代码

 

or:

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

 

posted @   Zhentiw  阅读(251)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2013-11-21 8. 利用反射机制, ListArray,intent来实现多Activity的切换
2013-11-21 7. Add song to Phone
2013-11-21 6. Activity life cycle
点击右上角即可分享
微信分享提示