【问题标题】:Assignment to Multiple Variables in JavaScriptJavaScript 中多个变量的赋值
【发布时间】:2018-08-15 11:45:55
【问题描述】:

一个对象的属性是否可以通过一次调用以某种方式分配给 JavaScript 中的多个变量(为方便起见)?

function getValues() {
    return {
        first: 1,
        second: 2
    };
}

function convenientAssignment() {
    let first = 0;
    let second = 0;
    {first, second} = getValues(); // <-- How can this be achieved?
    console.log("Values:", first, second);
}

不使用单独的赋值,如下所示:

let values = getValues();
first = values.first;
second = values.second;

这个问题与并发无关。

【问题讨论】:

标签: javascript variable-assignment destructuring


【解决方案1】:

您非常接近,使用object destructuring 将对象值放入变量中。

function simultaneous() {
    const {first, second} = getValues(); // <-- et voila!
    console.log("Values:", first, second);
}

在你的例子中,你的变量已经被声明了,你可以这样做:

function convenientAssignment() {
    let first = 0;
    let second = 0;
    ({first, second} = getValues()); // <-- et voila!
    console.log("Values:", first, second);
}

【讨论】:

  • 如果变量之前已经声明过怎么办,例如类成员?
  • 谢谢!伟大的! google 这个很难。现在我知道它叫做object destructuring
【解决方案2】:

这几乎就是 destructuring assignment 应该做的事情:

function getValues() {
    return {
        first: 1,
        second: 2
    };
}

let { first, second } = getValues();

console.log( first, second );
// 1 2

【讨论】:

    【解决方案3】:

    在您的特定情况下,由于您已经声明了 first 和 second,因此您需要将解构赋值包装在括号 () 中,如下所示:

    function getValues() {
        return {
            first: 1,
            second: 2
        };
    }
    
    function convenientAssignment() {
        let first = 0;
        let second = 0;
        ({first, second} = getValues()); // <-- Note the (...)
        console.log("Values:", first, second);
    }
    

    因为{first, second} 本身被认为是一个块。

    【讨论】:

      猜你喜欢
      • 2014-03-22
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 2014-02-26
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多