Javascript NodeJS:中断数组。一些循环
我有以下函数,它接收JSON数组模板并返回JSON对象 代码执行console.log。但是,它总是在函数末尾返回null。有什么想法吗Javascript NodeJS:中断数组。一些循环,javascript,arrays,json,node.js,Javascript,Arrays,Json,Node.js,我有以下函数,它接收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];
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 下面是一个工作示例 使用
.find
而不是。一些
。我们总是希望得到一个目标
函数getTemplate(模板,myId){
返回templates.find(template=>template.id==myId);
}
变量数组=
[
{
“id”:80,
“名称”:“模板1”
},
{
“id”:81,
“名称”:“模板2”
}
]
log(getTemplate(数组,80))代码>
返回模板[obj]
将在的上下文中返回。some(function)
当然。some
不是在数组中查找特定项的正确方法。@George:是的,它将向返回真实值。some
函数将告诉您存在正确的模板,最后只返回空值。@Cerbrus那么我该如何返回该值呢?@Cerbrus.find()
是首选,因为它会在找到值时停止迭代,而.filter()
不会。这不是.filter
的工作方式。@Cerbrus谢谢,我刚刚意识到,我们应该使用.find
。我已经更新了我的答案。