【问题标题】:Tree map method code in JavaScript about callbackJavaScript中关于回调的树形图方法代码
【发布时间】:2020-06-26 08:45:43
【问题描述】:

我想做一个树形图的方法,但是我做不到。我无法理解回调函数。我不知道你为什么在那里使用回调函数。

Tree.prototype.map = function(callback) {
  const newTree = new Tree(callback(this.value));

  function childCheck(child, newTree){
    for(let i=0; i<child.length; i++){
      newTree.addChild(callback(child[i].value))
      if(child[i].children){
        childCheck(child[i].children, newTree.children[i])        
      }
    }
  }
  childCheck(this.children, newTree)
  return newTree
  
};

我无法理解“回调(this.value)”和“回调(child[i].value)”。为什么参数使用回调?起初,我只是使用了 'this.value',但没有很好地实现。 我知道回调函数是异步的,它是在 Array.prototype.map(callback) 中实现的。

【问题讨论】:

  • 这里的回调看起来像是被调用者用来创建一个newTree节点,如果这个函数做到了,那么它只能创建一种类型的treeNode..
  • "我知道回调函数是异步的" - 不,它是一个同步回调。你没有一个如何调用这个方法的例子吗?

标签: javascript dictionary data-structures callback tree


【解决方案1】:

此处定义的map 方法提供的功能与本机map 方法在Array 上提供的功能相似。 map 的目的是创建一个具有相同形状的新数据结构,但原始数据的每个值都已由给定函数“映射”(转换、转换……)。例如,使用数组,您可以这样做:

function double(x) {
    return x * 2;
}
let arr = [1, 2, 3];
let result = arr.map(double);
console.log(result);

上面的 sn-p 创建了一个新数组,它具有相同数量的值,但每个值都是该位置原始值的两倍。

如果您想自己实现 map,您可以编写一个以函数为参数的函数。让我们暂时假设还没有数组的map 方法,那么您可以为它创建一个方法:

Array.prototype.myMap = function (callback) {
    let result = []; //  create a new array
    for (let value of this) {
        // create a new entry in the new array, and 
        //    give it the original value, but translated
        //    by the provided mapper (callback)
        result.push(callback(value));
    }
    return result;  // return the new array
};

// Demo of myMap:
function double(x) {
    return x * 2;
}
let arr = [1, 2, 3];
let result = arr.myMap(double);
console.log(result);

现在再次查看 Tree 的 map 函数。该函数首先创建一个新树,并“映射”原始根值,因此在原始树上调用回调,以便获取新树根的转换值。

然后它调用一个递归函数childCheck,它按预定顺序访问原始树中的每个其他节点。对于每个节点,它在新树中(在同一位置)创建一个新节点,然后为它提供来自原始节点的值,由回调函数映射(转换)。原理与Array.prototype.map 相同。当然,树结构比平面数组结构要复杂一些,因此它增加了对树进行递归遍历的复杂性。但其余的其实都是一样的原理。

【讨论】:

    猜你喜欢
    • 2012-08-02
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多