[英]The double for-loop do not get the return data
Why my code is not count
? 为什么我的代码count
?
var a = {
count: [{label:'a', value: 'a'}],
next: [{label:'b', value: 'b'}],
previous: [{label:'c', value: 'c'}],
}
function get_item() {
var x = "a"
for (let item in a){
a[item].forEach(obj => {
console.log(obj.value, x )
if(obj.value === x) {
return item
}
})
}
}
console.log(get_item())
the console logs are bellow: 控制台日志如下:
a a
b a
c a
undefined
you see the aa
, but why it do not is the count
rather than undefined
? 您看到了aa
,但是为什么它不是count
而不是undefined
?
below solution may work for you: 以下解决方案可能适合您:
var a = {
count: [{label:'a', value: 'a'}],
next: [{label:'b', value: 'b'}],
previous: [{label:'c', value: 'c'}]
}
function get_item() {
var x = "a"
for (let item in a){
let resultItem = a[item].find((obj)=>{ return obj.value === x });
if(resultItem) return item //you can also return 'resultItem';
}
}
console.log(get_item())
change your function as such. 这样改变你的功能。
var a = { count: [{label:'a', value: 'a'}], next: [{label:'b', value: 'b'}], previous: [{label:'c', value: 'c'}], } function get_item() { var x = "w" var retItem = undefined for (let item in a){ a[item].forEach(obj => { if(obj.value === x) { retItem = item } }) } return retItem; } console.log(get_item())
Here we just assign the result into a variable retItem
. 在这里,我们只是将结果分配给变量retItem
。 If we find something we return it, or we just return undefined 如果找到东西,我们将其返回,否则我们将返回未定义的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.