我有一个接受回调作为参数的映射方法,但是我不断收到此错误JavaScript

时间:2020-03-12 05:06:53

标签: javascript function scope

我对为什么'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并非功能?为什么呢?

1 个答案:

答案 0 :(得分:0)

.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);