如何访问foreach中的范围以获取变量值?
var fruitCollection = ['Grape','Orange','Banana'];
// give me a .txt file with the recipe for each fruit
var fruitsNeeded = function(){
fruitCollection.forEach(function(fruit) {
var fruitRecipe = fruit.toLowerCase() + '.txt';
return fruitRecipe;
});
}
fruitsNeeded(); // undefined
编辑预期输出:
// grape.txt
// orange.txt
// banana.txt
答案 0 :(得分:2)
您无法从ECHO ON
函数
forEach()为每个数组元素执行一次回调函数;与map()或reduce()不同,始终返回值未定义且不可链接。
您可以使用forEach
功能
map
ES6摘录:
var fruitCollection = ['Grape','Orange','Banana'];
var fruitsNeeded = function(){
return fruitCollection.map(function(fruit) {
return fruit.toLowerCase() + '.txt';
});
}

答案 1 :(得分:2)
另一个选择是构建一个数组并返回整个数组:
var fruitCollection = ['Grape','Orange','Banana'];
// give me a .txt file with the recipe for each fruit
var fruitsNeeded = function(){
var fruitRecipeList = [];
fruitCollection.forEach(function(fruit) {
var fruitRecipe = fruit.toLowerCase() + '.txt';
fruitRecipeList.push(fruitRecipe);
});
return fruitRecipeList;
}
fruitsNeeded();
答案 2 :(得分:0)
forEach
没有返回值;它只是一种在数组上执行的方法。您可能需要map
:
var fruits = fruitCollection.map(function(fruit) {
var fruitRecipe = fruit.toLowerCase() + '.txt';
return fruitRecipe;
});
// fruits = ['grape.txt','orange.txt','banana.txt']
答案 3 :(得分:0)
而不是从forEach返回一个值,您可以将它们添加到另一个全局范围变量中。
像这样:
var fruitCollection = ['Grape','Orange','Banana'];
var fruitFiles = [] ;
// give me a .txt file with the recipe for each fruit
var fruitsNeeded = function(){
fruitCollection.forEach(function(fruit) {
var fruitRecipe = fruit.toLowerCase() + '.txt';
fruitFiles.push(fruitRecipe) ;
});
return fruitFiles ;
}
fruitsNeeded(); // ["grape.txt", "orange.txt", "banana.txt"]
我希望这有帮助,左雅各布