return false or true while iterating an array of object
This question already has an answer here:
如果在回调中返回真值,可以使用Array#some
停止迭代的Array#some
。
var array = [{ name: 'paul', age:20 }, { name: 'john', age:30 }, { name: 'albert', age:40 }],
find = function(array, name) {
return array.some(function(object) {
return object.name === name;
});
};
console.log(find(array, 'paul')); // true
console.log(find(array, 'maria')); // false
You are returning in the forEach(function(i) {})
, which is only returning in the inside function function(i) {}
, that does not help return from the outer function find()
. Also, your logic with return false;
seems also problematic. Simply use normal for
loops would be fine.
var array = [
{name:'paul',age:20},
{name:'john',age:30},
{name:'albert',age:40}
];
var find = function(arr, name) {
for (let i of arr) {
if(i.name === name){
console.log('found ' + name);
return true;
}
}
console.log(name + ' not there');
return false;
};
find(array, 'paul');
find(array, 'maria');
停止使用forEach
方法,并尝试使用它:
var array = [
{name:'paul',age:20},
{name:'john',age:30},
{name:'albert',age:40}
];
var find = function(arr){
var returnValue = false;
for (var i = 0; i <= arr.length; i++) {
if(arr[i].name === 'john') {
ret = true;
break;
}
}
return returnValue;
};
find(array);
链接地址: http://www.djcxy.com/p/70056.html
上一篇: forEach回调的返回值在哪里?
下一篇: 迭代对象数组时返回false或true