The content of this article is about the usage of return when using angularjs.foreach. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
When writing a comparison to see if there is an object in the array object, it returns true if it exists and false if it fails. When returning, I found that there is no exit method and tested it myself.
First write An array object is then compared cyclically using the forEach method of angularjs. When there is an object named 2, true is output and returned, otherwise false is output and returned.
self.test = function() { var testArray = [{name: 1},{name:2},{name:3}]; angular.forEach(testArray, function(value, key){ if (value.name == 2) {console.log(true + ' pass the test');return;} console.log(value.name + ' pass'); }); console.log(false + ' pass the test'); return false; }();
At first I thought that when value.name = is found = 2 elements, the method will return directly, so it should only output 1 pass, true pass the test and then the program ends, but the output result is like this:
It turns out that the return in forEach actually only plays the role of continue in the for loop.
Then print out the return value of the forEach loop and the return value of the execution function:
The forEach function returns a looped array, and the return value of the function is false. This means that return in forEach does not work, it only functions as continue. Function.
I searched online, but there is no explanation of the reason..
Solution: Use a temporary variable to store the result, and when the conditions are the same, change the result to true:
self.test = function() { var testArray = [{name: 1},{name:2},{name:3}]; var result = false; angular.forEach(testArray, function(value, key){ if (value.name == 2) {result = true;} }); return result; }; console.log(self.test());
Although the correct return value can be obtained in this way, it cannot prevent the loop of forEach. I think forEach should be used to traverse the array elements to do some operations. Something like this should be used The for loop is better.
The above is the detailed content of How to use return when using angularjs.foreach. For more information, please follow other related articles on the PHP Chinese website!