gpt4 book ai didi

javascript - 没有 var、let 或 const 的对象解构

转载 作者:IT王子 更新时间:2023-10-29 02:50:32 27 4
gpt4 key购买 nike

如果前面没有 var 关键字,为什么对象解构会抛出错误?

{a, b} = {a: 1, b: 2};

抛出 SyntaxError:预期的表达式,得到 '='

下面三个例子没有问题

var {a, b} = {a: 1, b: 2};
var [c, d] = [1, 2];
[e, f] = [1, 2];

奖励问题:为什么我们不需要 var 来解构数组?

我在做类似的事情时遇到了问题

function () {
var {a, b} = objectReturningFunction();

// Now a and b are local variables in the function, right?
// So why can't I assign values to them?

{a, b} = objectReturningFunction();
}

最佳答案

问题源于 {...} 运算符在 JavaScript 中具有多重含义。

{ 出现在 Statement 的开头时,它总是表示 block ,无法分配给。如果它稍后出现在语句中作为表达式,那么它将表示一个对象。

var 有助于做出这种区分,因为它后面不能跟语句grouping parenthesis 也是如此。 :

( {a, b} = objectReturningFunction() );

来自他们的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assignment_separate_from_declaration_2

Notes: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

关于javascript - 没有 var、let 或 const 的对象解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27386234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com