我想知道下面的行被称为什么样的语法。
var that = {}, first, last;
注意:我在这个网站上发现了一个关于这个问题的帖子,但是他们说必须在右边的变量周围添加[]以使其成为一个数组。但是下面的代码确实有效。
代码:
var LinkedList = function(e){
var that = {}, first, last;
that.push = function(value){
var node = new Node(value);
if(first == null){
first = last = node;
}else{
last.next = node;
last = node;
}
};
that.pop = function(){
var value = first;
first = first.next;
return value;
};
that.remove = function(index) {
var i = 0;
var current = first, previous;
if(index === 0){
//handle special case - first node
first = current.next;
}else{
while(i++ < index){
//set previous to first node
previous = current;
//set current to the next one
current = current.next
}
//skip to the next node
previous.next = current.next;
}
return current.value;
};
var Node = function(value){
this.value = value;
var next = {};
};
return that;
};
答案 0 :(得分:3)
var that = {}, first, last;
类似于
var that = {};
var first;
var last;
我们正在使用空对象初始化that
,而first
和last
未初始化。因此,它们将具有默认值undefined
。
JavaScript从左到右为单个语句中声明的变量赋值。那么,以下
var that = {}, first, last = that;
console.log(that, first, last);
将打印
{} undefined {}
其中
var that = last, first, last = 1;
console.log(that, first, last);
会打印
undefined undefined 1
因为,在that
分配last
时,last
的值尚未定义。所以,它将是undefined
。这就是为什么that
是undefined
。
答案 1 :(得分:1)
这只是创建多个变量的简便方法。如果写成:
,可能会更清楚var that = {},
first,
last;
相当于:
var that = {};
var first;
var last;