在JavaScript中,链接分配好吗? [英] In JavaScript, is chained assignment okay?

查看:139
本文介绍了在JavaScript中,链接分配好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对JS或其语法不是新手,但有时候,语言的语义有时让我感到难过。在今天的工作中,一位同事提到了这一点:

  var a = b = []; 



<$ p $不同p> var a = [],b = [];

  var a = []; var b = []; 

因为第一个版本实际上将对空数组的引用分配给a和b。我不能完全接受这一点,但我不确定。你们都在想什么?

解决方案

是的,它们不一样。 var a = b = [] 相当于

  var a; 
b = [];
a = b;

不仅 a b 获得相同的值(对同一个空数组的引用), b 根本没有声明。在ECMAScript 5及更高版本的严格模式中,这将抛出 ReferenceError ;否则,除非范围内已有变量 b ,否则 b 将自动创建为全局对象的属性,类似于全局变量,无论代码在哪里,甚至在函数内部。哪个不好。



你可以很容易地看到这个:

 (function(){
var a = b = [];
})();

window.console.log(b); //显示[]


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 = [];

is not the same as

var a = [], b = [];

or

var a = []; var 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?

解决方案

Yes, they're not the same. var a = b = [] is equivalent to

var a;
b = [];
a = 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 = [];
})();

window.console.log(b); // Shows []

这篇关于在JavaScript中,链接分配好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆