foreach返回对象属性javascript [英] foreach return object property javascript
问题描述
在下面的代码中,有人可以解释为什么使用for循环返回object属性但不使用forEach。
它是与返回对象引用相关的东西还是特定于数组上的forEach循环的东西?
In the following code, can somebody explain why object property is returned using a for loop but not using a forEach. Is it something related to returning object references or is it something specific to forEach loop on an array ?
var empModule = (function(){
var empArray = [{
"name":"Aish",
"age":"27",
"location": "All"
},{
"name":"Anu",
"age":"26",
"location": "Muz"
},{
"name":"Vern",
"age":"25",
"location": "Mang"
}];
var searchAge = function(name){
for(var i=0;i<empArray.length;i++) {
if(empArray[i].name === name) {
return empArray[i].age;
}
};
};
var searchLocation = function(name){
empArray.forEach(function(obj){
if(name === obj.name) {
return obj.location;
}
});
};
return {
findAge: searchAge,
findLocation: searchLocation
};
})();
var secAge = empModule.findAge("Anu");
console.log(secAge); // Correct Output
var thirdLoc = empModule.findLocation("Vern");
console.log(thirdLoc); // Returns undefined
推荐答案
返回
返回它所在的函数。在 for ..
示例中,那是 searchAge
。当你使用 forEach()
时,你传递一个回调函数,所以你将值返回给该回调。你永远不会在 searchLocation
中返回任何内容。
return
returns to the function it's in. In the for..
example, that's searchAge
. When you use forEach()
, you pass it a callback function, and so you return the value to that callback. You never return anything in searchLocation
.
你应该只使用常规来...
在这里循环两次。
You should just use the regular for..
loop both times here.
这篇关于foreach返回对象属性javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!