查找数组值然后用角的forEach返回true [英] Find value in array then return true with Angular forEach
问题描述
我学习JavaScript和AngularJS。
I'm learning JavaScript and AngularJS.
这就是这个code之间的区别?
What's the difference between this code?
function isInArrayNgForeach(field, arr) {
angular.forEach(arr, function(value, key) {
if(field == value)
return true;
});
return false;
} // This returns always false
function isInArrayJavaScript(field, arr) {
for(var i = 0; i < arr.length; i++) {
if(field == arr[i])
return true;
}
return false;
} // This works fine
function isInArray() {
var testArr = ['stack', 'over', 'flow'];
console.log(isInArrayNgForeach('stack', testArr)); // return false
console.log(isInArrayJavaScript('stack', testArr)); // return true
}
我的问题是:为什么 isInArrayNgForeach 总是返回的假的?我认为,因为在函数中的函数,但我不知道为什么。
My question is: why isInArrayNgForeach always return false? I assume that because there is a function inside of the function, but I'm not sure why.
推荐答案
第一个选项是不同的,因为返回true;
从函数作为参数传递给返回的forEach
函数不能从外部函数 isInArrayNgForeach
,这就是为什么最后一行返回false; 当在foreach完成code>被总称。这使得该函数返回false始终。
The first option is different because return true;
returns from the function which is passed as parameter to forEach
function not from the outer function isInArrayNgForeach
and that's why the last line return false;
gets called always when the forEach finishes. Which makes the function return false always.
如果你改变了code这样,TT将返回预期的结果:
If you change the code like this, tt will return expected result:
function isInArrayNgForeach(field, arr) {
var result = false;
angular.forEach(arr, function(value, key) {
if(field == value)
result = true;
});
return result;
}
这篇关于查找数组值然后用角的forEach返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!