JavaScript解构赋值不是语法糖,而是改变变量绑定行为的特性;数组按索引严格匹配,对象按属性名匹配,均支持默认值、嵌套及扩展运算符,但对null/undefined会报错,且不处理不可枚举属性。
JavaScript 的解构赋值不是语法糖,而是实实在在改变变量绑定行为的特性;用错地方会静默失败或产生意外的 undefined。
数组解构按索引位置匹配,不看值。如果源数组长度不足,对应变量得是 undefined,除非你设默认值。
const [a, , c] = [1, 2, 3]; // a=1, c=3
undefined?给变量加默认值:const [x = 0, y = 0] = [5]; // x=5, y=0
const [first, ...rest] = [1, 2, 3, 4]; // rest = [2, 3, 4]
const [a, [b, c]] = [1, [2, 3]];
对象解构看的是属性名(key),不是变量名。左边写的是「要取哪个属性」,右边才是「存到哪个变量」。
const { name } = { username
: 'Alice' }; // name 是 undefined,因为没这个 keyconst { username: name } = { username: 'Alice' }; // name = 'Alice'
const { age = 18 } = {}; // age = 18
const { user: { id, profile: { city } } } = { user: { id: 101, profile: { city: 'Beijing' } } };
把解构写在函数形参里,能省掉手动取值,但要注意传入对象必须有对应属性,否则默认值只在解构时生效。
function connect({ host = 'localhost', port = 3000, timeout = 5000 }) {
console.log(`Connecting to ${host}:${port} (timeout: ${timeout}ms)`);
}
connect({ host: 'api.example.com', timeout: 3000 }); // port 自动 fallback 到 3000
connect({}); // 全部用默认值
null 或 undefined,会报 Cannot destructure property 'xxx' of 'undefined'
function connect({ host = 'localhost', port = 3000 } = {}) { ... }
Object.defineProperty(obj, 'hidden', { value: 42, enumerable: false }))解构出来的变量是新绑定,但对对象/数组内部的引用不变——改 obj.prop 会影响原对象,但重新赋值 prop = {} 不影响原对象。
const { config } = obj; config.url = '/new'; // 原 obj.config.url 也被改了
null 或 undefined,哪怕加了默认值也不行(默认值只对缺失属性生效)真正容易被忽略的,是解构时的“属性存在性”判断逻辑——它不等于“值是否 falsy”,而是严格检查 key 是否在对象自身属性中,in 操作符的行为一致,但很多人误以为 { a: 0 }.a || 'default' 和解构默认值等价,其实不是。