[英]JavaScript: Why I get `undefined` when I use an assignment with destructuring?
JavaScript, Google Chrome JavaScript,谷歌浏览器
This is my code example. 这是我的代码示例。 Why I get the undefined
values? 为什么我得到undefined
值?
let foo = {name: 'Bob', age: 24}; let {name, age} = foo; console.log(name); // 'Bob' console.log(age); // 24 foo = {color: 'red', result: true}; ({name, age} = foo); console.log(name); // "undefined" instead of 'red' console.log(age); // undefined instead of true
Destructuring the way you did it will match on the keys, not position (you can't really depend on the key order in objects). 解构它的方式将取决于键,而不是位置(您不能真正依赖于对象中的键顺序)。
const {foo} = {foo: "bar"}
is the equivalent of saying 相当于说
const foo = ({foo: "bar"}).foo
According to the MDN docs , destructuring assignment for structures is based on property names. 根据MDN文档 ,结构的销毁分配基于属性名称。 For your second assignment, since your object doesn't have properties name
and age
, those variables become undefined. 对于您的第二次分配,由于您的对象没有属性name
和age
,这些变量将变为未定义。
If you want to rename properties when assigning to variables, you can use the following syntax: 如果要在分配变量时重命名属性,则可以使用以下语法:
foo = {color: 'red', result: true};
({color: name, result: age} = foo);
That will assign the color
property of foo
to the variable name
and the result
property to age
. 这会将foo
的color
属性分配给变量name
,并将result
属性分配给age
。
Take a look at how the code is transpiled using babel and it becomes really clear what is happening. 看一下如何使用babel来转译代码,这很清楚发生了什么。 Using the babel console 使用babel控制台
'use strict';
var foo = { name: 'Bob', age: 24 };
var _foo = foo,
name = _foo.name,
age = _foo.age;
console.log(name); // 'Bob'
console.log(age); // 24
foo = { color: 'red', result: true };
var _foo2 = foo;
name = _foo2.name;
age = _foo2.age;
console.log(name); // "undefined" instead of 'red'
console.log(age); // undefined instead of true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.