与javascript中的对象数据类型混淆

时间:2015-06-11 19:06:03

标签: javascript

请看下面的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());

1 个答案:

答案 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/

相关问题