Created
October 31, 2011 16:20
-
-
Save zhuangya/1327877 to your computer and use it in GitHub Desktop.
indexOf prototype for IE 9-
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Refs: | |
* http://nootn.com/blog/Develop/35/ | |
* http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/#comment-57199 | |
* http://ecma262-5.com/ELS5_HTML.htm#Section_15.4.4.14 | |
*/ | |
if (!Array.prototype.indexOf) { | |
Array.prototype.indexOf = function(el, index) { | |
var n = this.length >>> 0, i = ~~index; | |
if (i < 0 ) i += n; | |
for (; i < n; i++) if (i in this && this[i] === el) return i; | |
return -1; | |
} | |
} |
@sofish 首先,这段不是我自己写的。我也是从网上找的。
然后关于 this.length >>> 0
这个。我刚试了一下。我觉得还是有必要的:
> var a = 1
undefined
> a.length
undefined
> a.length >>> 0
0
> 0 + a.length
NaN
尽管真的在call的时候出现这种情况的概率微乎其微。但是保证程序健壮终归不是什么坏事 :)
这是扩展 Array 的。.indexOf 执行的 context 不是 Array,那么应该让他自然报错啊,看一下 [].length 永远都是大于或者等于0。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
和同事讨论了一下,似乎下面这个是没必要的。问一下为什么需要
this.length >>>0
的存在?我们已经是 Array.prototype 了,怕 this 不是 Array?try this one: