为什么在Internet Explorer中indexOf方法无法正常工作?

6

这个函数在表单的onSubmit期间执行,在Firefox和Chrome中运行良好,但在IE中却不行。我怀疑是indexOf的问题,但我似乎找不到让它正常工作的方法。

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;
}

}

变量“suburbs”包含什么内容? - Tim
这是一个字符串数组,类似于“郊区名称(邮政编码)”。 - David
可能是重复的问题:为什么indexOf在IE8上不能用于数组?请参见以下链接:如何为IE浏览器修复JavaScript中的Array indexOf(),Internet Explorer的Array indexOf实现。 - Christian C. Salvadó
对于这个问题的详细解释以及不仅适用于indexOf而且适用于IE中其他缺失的数组函数的解决方法,请查看StackOverflow问题https://dev59.com/uHE85IYBdhLWcg3waCtT - Luis Perez
就我个人而言,我有一个开发环境,在那里它可以在IE11上运行,但是当我将其推广到我的测试环境时,它停止工作了?!?所以就像IE在某个地方有一个半成品的实现。 - gordon
4个回答

18

IE浏览器在Array上没有这个方法,但是你可以自己添加,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;
  };
}

如果缺少.indexOf()(此时表示您在使用IE<9),则可以添加它并使用它。至于为什么连IE8都没有这个功能?我也无能为力...


这似乎没有起作用,并且也使得在Firefox中停止工作。这需要放置在函数调用后还是脚本开头? - David
@David:在调用之前需要先声明。 - Cristian Sanchez

10

0

在 MSIE 11 上使用 indexOf() 函数时,它不支持非字符串变量。在 suburbs 中添加 .toString() 即可解决此问题。


-1

使用关联数组时,此函数效果不佳。

如果您将该函数放入代码中并执行以下操作:

var a = new Array();

a["one"] = "1";

for(var i in a){

   alert(i)

}

你得到了0,indexOf的意思是你将indexOf作为每个数组的键插入了进去

但是数组应该只有一个键,那就是"one"

使用jQuery吧!

-Mekias


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接