【问题标题】:NodeJS: break Array.some loop [duplicate]NodeJS:打破Array.some循环[重复]
【发布时间】:2017-04-10 13:13:11
【问题描述】:

我有以下函数,它接收一个 JSON 数组模板并返回一个 JSON 对象。

代码执行console.log。但是,它总是在函数末尾返回 null。有什么想法吗?

function getTemplate(templates, myId) {
  Object.keys(templates).some(obj => {
    if (templates[obj].id === myId) {
      console.log('HELLO');
      return templates[obj];
    }
  });
  return null;
}

模板数组

[
    {
        "id": 80,
        "name": "template 1"
    },
    {
        "id": 81,
        "name": "template 2"
    }
]

但是,它总是返回 null。

【问题讨论】:

  • return templates[obj]; 肯定会在.some(function) 的上下文中返回
  • .some 不是在数组中查找特定条目的正确方法。
  • @George:是的,它会返回一个真实值给.some 函数,它会告诉你正确的模板存在,最后只给return null
  • @Cerbrus 那么我该如何返回该值呢?
  • @Cerbrus .find() 是首选,因为它会在找到值时停止迭代,而 .filter() 不会。

标签: javascript arrays json node.js


【解决方案1】:

这是工作示例,

使用.find 而不是.some。我们总是希望得到一个对象。

function getTemplate(templates, myId) {
  return templates.find(template => template.id === myId);
}

var array =
[
    {
        "id": 80,
        "name": "template 1"
    },
    {
        "id": 81,
        "name": "template 2"
    }
]
console.log(getTemplate(array, 80));

【讨论】:

  • .filter 不是这样工作的。
  • @Cerbrus 谢谢,我刚刚意识到,我们应该改用.find。我已经更新了我的答案。
猜你喜欢
  • 2011-12-08
  • 2010-10-13
  • 2013-03-09
  • 2015-03-03
  • 2017-06-04
  • 1970-01-01
相关资源
最近更新 更多