Javascript map method creating 'Object doesn't support this property or method ' in Internet Explorer (IE)?

吃可爱长大的小学妹 提交于 2021-01-28 19:40:14

问题


javascript code shows error in Internet Explorer but not in FF.

$(document).ready(function(){




var countries = [
  ["Afghanistan","Af"],
  ["Åland Islands","Ax"],
  ["Zimbabwe","Zw"]
];

 var countryNames = countries.map(function(country){
  return {
    /*label: '<div class="flag '+country[1].toLowerCase()+'">'+country[0]+'</div>',*/
    value: country[0]
  }

  var my_var=countryNames();
}); 

});

In IE 8 developer tool, if I debug js, the error message is :' Object doesn't support this property or method'. And the error is indicated at the snippet starting with the line :

var countryNames = countries.map(function(country){

How to make the code work in IE ?


回答1:


The Array.prototype.map() function is only supported in Internet Explorer 9, so that code won't work in earlier versions of the browser. Since you've tagged the question as jQuery, you could use the jQuery.map() function instead:

var countryNames = jQuery.map(countries, function(country) {
    return { 
        value: country[0]
    }
});

jsFiddle DEMO tested using Internet Explorer 9 in IE7 mode.




回答2:


Use Jquery .each() instead http://api.jquery.com/jQuery.each/

var countryNames = [];    
$.each(countries, function(index, value){
    countryNames.push(value[0]);
}



回答3:


Not all versions (if any) have Array.prototype.map

This is a polyfill/MonkeyPatch you can use to support it under IE -- but including this code may cause problems if you use for ... in on your arrays.

Array.prototype.map




回答4:


  var my_var=countryNames();
}); 

should be:

}); 
  var my_var=countryNames;

Worked in IE9 for me.

Or you can you use $.each like Neil Kennedy said.



来源:https://stackoverflow.com/questions/12491444/javascript-map-method-creating-object-doesnt-support-this-property-or-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!