JavaScript 中的多个变量赋值

Assignment to Multiple Variables in JavaScript

是否可以通过一次调用(为方便起见)将对象的属性以某种方式分配给 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;

此题与并发无关

你非常接近,使用 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);
}

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

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

let { first, second } = getValues();

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

在您的特定情况下,因为您已经声明了 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} 本身被认为是一个块。