Javascript 为什么 indexOf 在 Internet Explorer 中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3697555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is indexOf not working in Internet Explorer?
提问by David
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.
此函数在表单 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;
}
}
回答by Nick Craver
IE simply doesn't have this method on Array, you can add it yourself though, from MDC:
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;
};
}
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...
这增加了.indexOf()如果缺少(在这一点上,这意味着你在IE <9是),那么你可以使用它。至于为什么连IE8都没有这个?在那里我帮不了你...
回答by jhanifen
If you are already using jQuery in your project you can use $.inArray()
如果您已经在项目中使用 jQuery,则可以使用 $.inArray()
回答by SpookySr
indexOf() on MSIE 11 and others it doesn't like non-string variables. On suburbs add .toString() and it should fix it.
indexOf() 在 MSIE 11 和其他它不喜欢非字符串变量。在郊区添加 .toString() 并且它应该修复它。
回答by Mekias
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, indexOfwhich means you inserted indexOfas a key to every array you create
你得到 0,indexOf这意味着你indexOf作为键插入你创建的每个数组
but the array should only have one key and that is "one"
但数组应该只有一个键,那就是“一”
use jQuery!
使用jQuery!
-Mekias
-梅基亚斯

