在 JavaScript 中,链式赋值好吗? [英] In JavaScript, is chained assignment okay?
问题描述
我对 JS 或其语法并不陌生,但有时,该语言的语义有时让我感到困惑.今天上班,同事提到了这个:
Am not new to JS or its syntax, but sometimes, the semantics of the language has me stumped at times. At work today, a colleague mentioned this:
var a = b = [];
与
var a = [], b = [];
或
var a = []; var b = [];
因为第一个版本实际上将空数组的引用分配给 a 和 b.我不能完全接受这是真的,但我不确定.大家怎么看?
since the first version actually assigns the reference to an empty array to a and b. I couldn't quite accept this as true, but I'm not sure. What do you all think?
推荐答案
是的,它们不一样.var a = b = []
等价于
Yes, they're not the same. var a = b = []
is equivalent to
var a;
b = [];
a = b;
不仅 a
和 b
都被分配了相同的值(对同一个空数组的引用),b
没有被声明根本.在 ECMAScript 5 及更高版本的严格模式中,这将抛出一个 ReferenceError
;否则,除非在作用域中已经有一个变量 b
,b
被静默创建为全局对象的一个属性,并且无论代码在哪里,它的行为都类似于全局变量,即使在函数内部.哪个不好.
Not only do both a
and b
get assigned the same value (a reference to the same empty array), b
is not declared at all. In strict mode in ECMAScript 5 and later, this will throw a ReferenceError
; otherwise, unless there is already a variable b
in scope, b
is silently created as a property of the global object and acts similarly to a global variable, wherever the code is, even inside a function. Which is not good.
您可以很容易地看到这一点:
You can see this quite easily:
(function() {
var a = b = [];
})();
console.log(b); // Shows []
这篇关于在 JavaScript 中,链式赋值好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!