这些代码中的“{}”和“()”有什么区别

What's the difference between `{}` and `()` in these code?

本文关键字:区别 什么 代码      更新时间:2023-09-26

>Destructuring_assignment#Assignment_without_declaration

它说:

左侧的 {a, b} 被视为块,而不是对象文字。

var a, b;
{a, b} = {a:1, b:2};//Syntax Error!
({a, b} = {a:1, b:2}); // it works

第二句中的"()"有什么作用?

为什么其中的"{}"被视为对象文字?

第一个尝试为块赋值,这是不正确的。第二个相当于

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

因此,这里您调用了一个构造函数,提供属性块并为其赋值。

语句在 Javascript 中不能以大括号开头:解构的陷阱

或者,可以使用以下表达式:

"",{a, b} = {a:1, b:2};
语句不以大括号开头

很重要,因为代码块以大括号开头。

我可以简单地引用您链接的示例旁边的突出显示的解释:

我认为这很清楚

赋值语句周围的 ( .. ) 是使用不带声明的对象文字解构赋值时必需的语法。

{a, b} = {a:1, b:2}不是有效的独立语法,因为左侧的{a, b}被视为块而不是对象文本。

但是,({a, b} = {a:1, b:2})是有效的,var {a, b} = {a:1, b:2}

我们不能为任何文字分配任何值,如数组、对象、字符串。

前任:[a] = [1];

{a} = {1};

"a" = "b";

但是我们可以使用逗号分隔符分配值

[a],{a} = {a:1};

输出:

[一] -- [1]

{a} -- {a:1}

注意:

1.对象文字不应在初始化中排在第一位。

2.In 字符串文本从不存储任何值。

() - 是 qualto 返回语句

无论你在 {} 中给出什么,它都会自动执行;

要检查,只需将代码 {return;} 放在函数中的任何位置,它将返回函数。

只需查看截取的代码即可理解。

var a =5;b=6;
console.log(JSON.stringify({a,b}));
//Output: {"a":5,"b":6}
[a,b],{a,b} = {"a":1, "b":2};
console.log(JSON.stringify([a,b]));
console.log(JSON.stringify({a,b}));
//Output: 
//[1,2]
//{"a":1,"b":2}
var name = (function(){return "lotus"});
console.log(name);
//Output: function(){return "lotus"}
name = (function(){return "lotus"})();
console.log(name);
//Output: lotus
name = ({a, b} = {a:3, b:4});
console.log(JSON.stringify(name));
//Output: {"a":3,"b":4}