gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:08:44 24 4
gpt4 key购买 nike

我想知道下面这行调用的是哪种语法。

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

最佳答案

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 的原因。

关于javascript - 在 Javascript 中将多个变量分配给一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27690628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com