在Javascript中将多个变量分配给一个变量?

时间:2014-12-29 14:21:58

标签: javascript

我想知道下面的行被称为什么样的语法。

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;
}; 

2 个答案:

答案 0 :(得分:3)

var that = {}, first, last;

类似于

var that = {};
var first;
var last;

我们正在使用空对象初始化that,而firstlast未初始化。因此,它们将具有默认值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。这就是为什么thatundefined

答案 1 :(得分:1)

这只是创建多个变量的简便方法。如果写成:

,可能会更清楚
var that = {}, 
    first, 
    last;

相当于:

var that = {};
var first;
var last;
相关问题