[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
分类:
ES6
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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