【问题标题】:Using destructuring assign vaules to already defined varibales使用解构将值分配给已定义的变量
【发布时间】:2019-07-12 13:37:00
【问题描述】:

根据 javascript.info,下面的代码应该可以工作, https://javascript.info/destructuring-assignment#object-destructuring

在我的项目中,我已经定义了一些变量,现在我正在尝试使用 destructuring 分配一个值 但是,我无法在下面的代码中运行。

// This also does not work.
let title, width, height;
myobj = {title: "Menu", width: 200, height: 100}
({title, width, height}) = myobj;
console.log(title);

// This also does not work.
let title, width, height;
myobj = {title: "Menu", width: 200, height: 100}
{title, width, height} = myobj;
console.log(title);

【问题讨论】:

    标签: javascript object destructuring


    【解决方案1】:

    您需要将整个表达式包裹在() 中,并在上一行添加分号

    来自Assignment without declaration

    使用没有声明的对象字面量解构赋值时,赋值语句周围的括号 ( ... ) 是必需的。

    您的 ( ... ) 表达式需要以分号开头,或者它可以用于执行上一行的函数。

    // This also does not work.
    let title, width, height;
    let myobj = { title: "Menu", width: 200, height: 100 }; // <- semicolon here
    ({ title, width, height } = myobj);
    console.log(title);

    【讨论】:

    • 谢谢,把我的代码改成;({ title, width, height } = myobj);
    猜你喜欢
    • 2019-01-17
    • 2021-11-22
    • 2021-06-19
    • 2022-01-01
    • 1970-01-01
    • 2019-06-25
    • 2014-08-20
    • 2013-03-15
    • 1970-01-01
    相关资源
    最近更新 更多