如果你有使用过JavaScript,你就应该知道Internet Explorer并没有实现ECMAScript的Array.prototype.indexOf()函数,这包括Internet Explorer 8。不过这不是个大问题,因为你可以通过以下代码在你的页面上扩展功能。
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
我应该在什么时候实现这个?
我是否应该在所有页面上包装它,并使用以下检查来检查原型函数是否存在,如果不存在,则继续扩展Array原型?
if (!Array.prototype.indexOf) {
// Implement function here
}
或者进行浏览器检查,如果是Internet Explorer,则仅实现它?
//Pseudo-code
if (browser == IE Style Browser) {
// Implement function here
}
Array.prototype.indexOf
不是ECMA-262/ECMAScript的一部分。请参见http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf。也许你想要使用的是`String.prototype.indexOf`... - Crescent FreshArray.indexOf
实现没有考虑负数起始索引。请参考 Mozilla 的建议临时实现:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf - nickf