Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  41] [ 1]  / answers: 1 / hits: 37505  / 10 Years ago, thu, july 31, 2014, 12:00:00

I'm learning JavaScript and AngularJS.



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
}


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.


More From » angularjs

 Answers
7

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.



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;
}

[#69977] Tuesday, July 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jordenfabiand

Total Points: 678
Total Questions: 107
Total Answers: 95

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;