我有一个接受回调作为参数的映射方法,但我一直得到这个错误JavaScript



我完全不明白为什么在我的情况下"cb"不是一个函数。

基本上我有一个"树"构造函数

this.value = value;
this.children = [];
};
Tree.prototype.addChild = function (value){
var newInstance = new Tree(value);
this.children.push(newInstance);
}
Tree.prototype.map = function(cb){
var copyTree = new Tree(this.value); //1
copyTree.value = cb(copyTree.value);
for (var i = 0; i < this.children.length; i++){ // i = 0; 2                 i = 0's value is 2
copyTree.addChild(new Tree.prototype.map(cb(this.children[i].value)))
}
return copyTree;
}

然后在控制台上,我通过了

var root1 = new Tree(1)
var branch1 = root1.addChild(2);
var branch2 = root1.addChild(3);

现在每次我调用

var newTree = root1.map(function (value) {
return value * 2 })

我总是犯这个错误。

VM1769 Script snippet %231:13 Uncaught TypeError: cb is not a function
at new Tree.map (VM1769 Script snippet %231:13)
at Tree.map (VM1769 Script snippet %231:19)
at <anonymous>:1:21

我知道我的映射方法可能不正确,但"cb"不是函数这一事实让我很困惑,我在.map调用中传递了一个匿名函数,但…"cb不是函数吗?为什么?

.map内部,您有一个要在this.children内部复制的树数组。由于数组是由树组成的,因此这些树已经有了.map方法,您可以调用该方法来创建该树的副本。更改

copyTree.addChild(new Tree.prototype.map(cb(this.children[i].value)))

copyTree.addChild(this.children[i].map(cb))

function Tree(value) {
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function(value) {
var newInstance = new Tree(value);
this.children.push(newInstance);
}
Tree.prototype.map = function(cb) {
var copyTree = new Tree(this.value);
copyTree.value = cb(copyTree.value);
for (var i = 0; i < this.children.length; i++) {
copyTree.addChild(this.children[i].map(cb))
}
return copyTree;
}
var root1 = new Tree(1)
var branch1 = root1.addChild(2);
var branch2 = root1.addChild(3);
var newTree = root1.map(function(value) {
return value * 2
})
console.log(newTree);

更易读,使用现代语法:

class Tree {
constructor(value) {
this.value = value;
this.children = [];
}
addChild(value) {
const newInstance = new Tree(value);
this.children.push(newInstance);
}
map(cb) {
const copyTree = new Tree(this.value);
copyTree.value = cb(copyTree.value);
for (const child of this.children) {
copyTree.addChild(child.map(cb))
}
return copyTree;
}
}
const root1 = new Tree(1)
const branch1 = root1.addChild(2);
const branch2 = root1.addChild(3);
const newTree = root1.map(value => value * 2);
console.log(newTree);

最新更新