请看下面的javascript代码,当我运行它时它给了undefined,我可能知道我在做错了吗?
var fruit ={
name:"mango",
color:"yellow",
nativeTo:["india","china"],
showName:function(){
return this.color + " " + this.name
},
foundIn: function (){
this.nativeTo.forEach(function(country){
return ( "found in "+ country)
})
}
}
alert (fruit.foundIn());
答案 0 :(得分:2)
将foundIn
更改为:
foundIn: function() {
return this.nativeTo.map(function(country) {
return "found in "+ country;
})
}
那会警告:
found in india,found in china
请注意使用map
代替forEach
- 您可以使用forEach
进行迭代,但是您需要在forEach
次迭代之外的变量来累积您的内容想要返回(字符串),然后你需要返回那个累积字符串。
JSFiddle:http://jsfiddle.net/a2s3hh39/