1

除了 jQuery,我对 JavaScript 还很陌生,我正在阅读 JavaScript 数组中的随机化以及使用带有随机数的 Array.sort 方法的缺点。我看到的建议是使用 Fisher-Yates shuffle。在查看此方法的 JavaScript 代码时:

Array.prototype.randomize = function()
{
    var i = this.length, j, temp;
    while ( --i )
    {
        j = Math.floor( Math.random() * (i - 1) );
        temp = this[i];
        this[i] = this[j];
        this[j] = temp;
    }
}

我被这行打动了:

var i = this.length, j, temp;

这里发生了什么?一个变量是否被赋予了多个值,或者这是某种东西的简写?

4

6 回答 6

5

一个变量永远不能同时有多个值。

您提供的代码是简写

var i = this.length;
var j;
var temp;

像上面这样的语法在大多数编程语言中都是合法的。

于 2013-08-12T18:43:39.713 回答
2

var i = this.length, j, temp;

是相同的 :

var i = this.length;
var j; // here the value is undefined
var temp; // same, temp has a an undefined value
于 2013-08-12T18:44:08.873 回答
2

不,它是以下的简写: var i = this.length; var j; var temp;

于 2013-08-12T18:44:48.523 回答
1

它只是在一行中多次声明变量。这相当于:

var i, j, temp;
i = this.length;

这相当于:

var i;
var j;
var temp;
i = this.length;
于 2013-08-12T18:47:49.197 回答
1

规范将变量声明定义为var关键字,后跟变量声明列表,以逗号分隔:

VariableStatement :
    var VariableDeclarationList ;

VariableDeclarationList :
    VariableDeclaration
    VariableDeclarationList , VariableDeclaration

注意 的递归定义VariableDeclarationList。这意味着一个var关键字后面可以有无限数量的变量声明。

因此

var foo, bar;

是相同的

var foo;
var bar;

相关问题:使用相同的 var 关键字初始化多个 javascript 变量有什么好处?

于 2013-08-12T18:51:45.767 回答
1

您正在创建三个变量,并且只有最左边的变量会产生一个值 - 在这种情况下,无论值this.length是什么。

正如其他所有回答您问题的人所指出的那样,它与以下内容相同:

var i = this.length;
var j, temp;

Java、C# 和 Visual Basic 等其他语言允许您创建具有类似语法的变量。IE:

IE:

// C# and Java
int i = this.length, j, temp;

// which is the same as:
int i = this.length;
int j, temp;

 

' Visual Basic
Dim i = this.length as Integer, j as Integer, temp as Integer

' Which is the same as:
Dim i = this.length as Integer
Dim j as Integer, temp as Integer
于 2013-08-12T18:45:01.660 回答