Why is indexOf not working in Internet Explorer?

倖福魔咒の 提交于 2020-02-02 03:05:26

问题


This function executes during the forms onSubmit, and works fine in Firefox and Chrome, but not in IE. I suspect it's indexOf, but I cannot seem to find a way to get it to work.

function checkSuburbMatch(e) {

var theSuburb = document.getElementById('suburb').value;
var thePostcode = document.getElementById('postcode').value;

var arrayNeedle = theSuburb + " (" + thePostcode + ")";

if(suburbs.indexOf(arrayNeedle) != -1) {
    alert("Suburb and Postcode match!");
    return false;
} else {
    alert("Suburb and Postcode do not match!");
    return false;
}

}

回答1:


IE simply doesn't have this method on Array, you can add it yourself though, from MDC:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

This adds .indexOf() if it's missing (at this point that means you're in IE<9) then you can use it. As for why even IE8 doesn't have this already? I can't help you there...




回答2:


If you are already using jQuery in your project you can use $.inArray()

http://api.jquery.com/jQuery.inArray/




回答3:


indexOf() on MSIE 11 and others it doesn't like non-string variables. On suburbs add .toString() and it should fix it.




回答4:


this function is bad when using associative arrays.

if you put that function in your code and do this

var a = new Array();

a["one"] = "1";

for(var i in a){

   alert(i)

}

You get 0, indexOf which means you inserted indexOf as a key to every array you create

but the array should only have one key and that is "one"

use jQuery!

-Mekias



来源:https://stackoverflow.com/questions/3697555/why-is-indexof-not-working-in-internet-explorer

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