为什么我的函数总是返回未定义的?

时间:2018-09-26 11:47:44

标签: javascript

我编写了一个函数来搜索嵌套对象。问题在于它返回了labels而不是预期的结果,该结果已正确记录在控制台中。那里发生了什么事?

undefined

实时示例:https://stackblitz.com/edit/js-dapzsy

2 个答案:

答案 0 :(得分:2)

只需在末尾添加return

return keys.map(key =>
    findVDOMNode(instance, vDOM[key].children));

您可以获取对象的值并对照实例进行检查。如果找到了对象,请同时检查该对象。如果发现该实例,请使用some进行短路迭代。

const
    in1 = [1, 2],
    in2 = [1, 2],
    vDOM = { 1: { ref: in1, children: { 2: { ref: in2, children: {} } } } },
    findVDOMNode = (instance, vDOM) => Object
        .values(vDOM)
        .some(v => v === instance
            || v && typeof v === 'object' && findVDOMNode(instance, v)
        );
  
console.log('res: ', findVDOMNode(in2, vDOM));

答案 1 :(得分:0)

您似乎在函数的最后一行中缺少地图上的return语句

const in1 = [1, 2];
const in2 = [1, 2];

const vDOM = {
  1: {
    ref: in1,
    children: {
      2: {
        ref: in2,
        children: {}
      }
    }
  }
}

const findVDOMNode = function(instance, vDOM) {
  const keys = Object.keys(vDOM);
  const foundKey = keys.find(key => vDOM[key].ref === instance);

  //console.log(foundKey, vDOM, "FK");

  if (!keys.length) {
    console.log('no keys');
    return;
  }
  if (foundKey) {
    console.log('found', vDOM[foundKey]);
    return true; //vDOM[foundKey];
  };
  ///added this return statement
  return keys.map(key =>
    findVDOMNode(instance, vDOM[key].children));
}

console.log('res: ', findVDOMNode(in2, vDOM));