【问题标题】:I can't return an object [closed]我不能返回一个对象[关闭]
【发布时间】:2021-06-24 22:44:31
【问题描述】:

我有一个这样的对象:

const obj = {
  name: 'john',
  children: [
    {
      name: 'Foo'
    },
    {
      name: 'Bar',
      children: [
        {
          name: 'Doe'
        }
      ]
    }
  ]
}

我必须创建一个函数来查找具有指定名称的对象。 我的代码可以找到具有名称的对象,但它不返回该对象。

const search = (node, name) => {
  return searchInObj(node, name);
};

const searchInObj = (obj, name) => {
  if (obj.name === nodeName) {
    return obj;
  } else {
    if (obj.children) {
      searchInArr(obj.children, name);
    }
  }
};

const searchInArr = (arr, name) => {
  for (let i = 0; i < arr.length; i++) {
    searchInObj(arr[i], name);
  }
};

如果我放

console.log(search(obj, 'Doe')) // return undefined

如果我寻找john,它就可以工作

【问题讨论】:

  • 您遗漏了一些 return 语句
  • 你试过调试你的函数吗?另外,我会使用 Array.prototype.some 在 children 数组中搜索,而不是在那里添加 searchInArr。然后递归将在 searchInObj 中进行。此外,undefined 作为返回值表示缺少返回语句,正如 Quentin 指出的那样。

标签: javascript function object


【解决方案1】:

返回 searchInObj 函数的结果。

  const obj = {
  name: 'john',
  children: [
    {
      name: 'Foo'
    },
    {
      name: 'Bar',
      children: [
        {
          name: 'Doe'
        }
      ]
    }
  ]
}

const search = (node, name) => {
  return searchInObj(node, name);
};

const searchInObj = (obj, name) => {
  if (obj.name === name) {
    return obj;
  } else {
    if (obj.children) {
      return searchInArr(obj.children, name);
    }
  }
};

const searchInArr = (arr, name) => {
  for (let i = 0; i < arr.length; i++) {
    const result = searchInObj(arr[i], name);
    if (result !== undefined) return result
  }
};

console.log(search(obj, 'Doe')) ///This will return object

【讨论】:

    【解决方案2】:

    只需添加return 语句,就像@quentin 说的那样

    const obj = {
      name: 'john',
      children: [
        {
          name: 'Foo'
        },
        {
          name: 'Bar',
          children: [
            {
              name: 'Doe'
            }
          ]
        }
      ]
    }
    
    const search = (node, name) => {
      return searchInObj(node, name);
    };
    
    const searchInObj = (obj, name) => {
      // Typo here? what is nodeName
      if (obj.name === name) {
        return obj;
      } else {
        if (obj.children) {
          // Added return 
          return searchInArr(obj.children, name);
        }
      }
    };
    
    const searchInArr = (arr, name) => {
      for (let i = 0; i < arr.length; i++) {
        // Return if found
        const result = searchInObj(arr[i], name);
        if (result !== undefined) return result
      }
    };
    
    console.log(search(obj, 'Doe'))

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 2013-07-07
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2015-01-15
      • 2014-03-18
      相关资源
      最近更新 更多