gpt4 book ai didi

递归中的 Javascript 'this' 上下文?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:33 25 4
gpt4 key购买 nike

在 JS 中编写一个简单的 BST 实现,但我遇到了一些我不明白的事情。代码如下:

var Node = function(time, value) {
// has time and value
this.time = time;
this.value = value;

this.left;
this.right;

// we have an insert method.
var insert = function(time, value) {
if (time <= this.time) {
// go left
if (!this.left) {
this.left = new Node(time, value);
} else {
this.left.insert(time, value);
}
} else {
// go right
if (!this.right) {
this.right = new Node(time, value);
} else {
this.right.insert(time, value);
}
}
}

this.insert = insert;

// we have a find method
var that = this;
var find = function(time) {
if (time === that.time) {
// we found the node, let's return this one
console.log("%%%" + **that.value**);
return **that.value**;
}

if (time > that.time) {
this.right.find(time);
} else {
this.left.find(time);
}
}

this.find = find;
}

var a1 = new Node(3, "aad");
a1.insert(9, "bbasd");
a1.insert(5, "caadfas");
a1.insert(10, "daddaf");

console.log(a1.find(3));
console.log(a1.find(5));
console.log(a1.find(9));
console.log(a1.find(10));

这个输出:

%%aad 
aad
%%caadfas
undefined
%%bbasd
undefined
%%daddaf
undefined

为什么控制台打印行有正确的 this.value 但返回的 this.value 是未定义的?

谢谢!

最佳答案

您不会返回通过“左”或“右”链接调用 .find() 的结果。您只是调用函数并丢弃结果。

相反:

if (time > that.time) {
return this.right.find(time);
} else {
return this.left.find(time);
}

关于递归中的 Javascript 'this' 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31839726/

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