gpt4 book ai didi

javascript - 变量始终为 NaN

转载 作者:行者123 更新时间:2023-12-02 18:56:43 25 4
gpt4 key购买 nike

我正在学习 JS(但对编程并不陌生)。因此,我尝试实现一个 LinkedList 只是为了玩转 JS。

除了 count 总是返回 NaN 之外,它工作正常。我用 google 搜索了一下,认为原因是我最初没有将 count 设置为数字,但我确实这样做了。

下面是我的代码:

function LinkedList() {
var head = null,
tail = null,
count = 0;

var insert = function add(data)
{
// Create the new node
var node = {
data: data,
next: null
};

// Check if list is empty
if(this.head == null)
{
this.head = node;
this.tail = node;
node.next = null;
}
// If node is not empty
else
{
var current = this.tail;
current.next = node;
this.tail = node;
node.next = null;
}

this.count++;
};

return {
Add: insert,
};
}

var list = new LinkedList();
list.Add("A");
list.Add("B");

最佳答案

this.count中的this指的是LinkedList对象的实例。该部分:

var head = null,
tail = null,
count = 0;

这些是私有(private)变量,不被视为 LinkedList 对象的属性。

您想要做的是:

this.head = null;
this.tail = null;
this.count = 0;

这将使 headtailcount 成为 LinkedList 对象的属性,以便您可以执行 this.count++ .

编辑:要将 headtailcount 保留为 LinkedList 对象的私有(private),您的其他代码会是这样的:

// Check if list is empty
if(head == null)
{
head = node;
tail = node;
node.next = null;
}
// If node is not empty
else
{
var current = tail;
current.next = node;
tail = node;
node.next = null;
}

count++;

还请记住,对象是按引用传递的。因此这适用于:

var current = tail;
current.next = node;
tail = node;
node.next = null;

更多:如果您希望 count 成为公共(public)属性,则不要返回:

 return {
Add: insert,
};

你需要这样做:

this.Add = insert;
return this;

以便在对象创建时返回当前对象上下文。

关于javascript - 变量始终为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15263662/

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