问题描述
在线阅读文档,我对如何在一行中正确定义多个JavaScript变量感到困惑。
Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line.
如果我想压缩以下代码,那么什么是适当的JavaScript严格方式在一行上定义多个javascript变量?
If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line?
var a = 0;
var b = 0;
是吗:
var a = b = 0;
或
var a = var b = 0;
等...
推荐答案
你想要依赖逗号,因为如果你依赖于多重赋值结构,你就会在一个或另一个角落里射击自己。
You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.
一个例子是:
>>> var a = b = c = [];
>>> c.push(1)
[1]
>>> a
[1]
它们都是指内存中的同一个对象,它们不是unique,因为任何时候你引用一个对象(数组,对象文字,函数)它都是通过引用而不是值传递的。因此,如果你只改变其中一个变量,并希望它们单独行动,你就不会得到你想要的东西,因为它们不是单个物体。
They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.
还有一个缺点在多重赋值中,辅助变量变为全局变量,并且您不希望泄漏到全局命名空间。
There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.
(function() { var a = global = 5 })();
alert(window.global) // 5
最好只使用逗号,最好是有很多空格,所以它是可读的:
It's best to just use commas and preferably with lots of whitespace so it's readable:
var a = 5
, b = 2
, c = 3
, d = {}
, e = [];
这篇关于如何在一行上定义多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!