JavaScript – 解构赋值 Destructuring Assignment
参考
Array Destructuring Assignment
old school
const items = [1, 2, 3]; const item1 = items[0]; const item2 = items[1]; const item3 = items[2];
一个一个从 array 拿出来, 再一个一个 assign 给每一个变量.
modern
const [item1, item2, item3] = [1, 2, 3];
一行里面做了 declare, assign, read from array. 3 个动作一气呵成.
get someone
const [, , value3] = [1, 2, 3];
with default value
const [v1] = []; // v1 = undefined const [v1 = 'default value'] = []; // v1 = 'default value' const [v1 = 'default value'] = ['value']; // v1 = 'value'
Object Destructuring Assignment
它和 Array 的用法差不多
const person = { name: 'Derrick', age: 11 };
const { name, age } = person;
with alias 别名
const person = { name: 'Derrick', age: 11 }; const { name: newName, age: newAge } = person; console.log(newName); console.log(newAge);
name: newName 中间使用了分号
with default value
const { name = 'Derrick', age } = {}; // name = 'Derrick' // age = undefined
nested
解构支持嵌套哦,
document.dispatchEvent( new CustomEvent('myevent', { detail: { tabName: 'tab name', }, }) );
监听时解构获取 tabName
document.addEventListener('myevent', ({ detail: { tabName } }) => { // do something... });
Common Use Case
上面的例子解构以后都被赋值到变量, 这个是最 common 的用法.
但其实你要 assign 到哪里都是可以的哦.
assign to parameters
function method1([v1, v2]) { console.log(v1); console.log(v2); } method1(['value1', 'value2']); function method2({ name, age }) { console.log(name); console.log(age); } method2({ name: 'Derrick', age: 11 });
assign to existing variables (swap value)
let v1 = 1; let v2 = 2; [v1, v2] = [v2, v1]; console.log(v1); // 2 console.log(v2); // 1
Mix cost and let when using destructuring assignment
参考: stackoverflow – How to mix const and let when using object or array destructuring assignment in ES6?
在 C# 可以这样 mix 着写
在 JS 则不行, 如果是要 declare const 或 let 那么就必须全部都是一样的, 同理如果是要 assign to exsiting variables 必须全部都是 existing.
解决方案就是多写几个 destructuring assignment 咯.
const array = [1, 2, 3]; let existingValue = 1; [existingValue] = array; const [, value2] = array; let [, , value3] = array;
是不是有一种, 一个一个写更好的感觉...哈哈
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· 【全网最全教程】使用最强DeepSeekR1+联网的火山引擎,没有生成长度限制,DeepSeek本体
2017-05-06 pdf can't copy text 无法复制文字