实现IE下Array.indexOf函数
我一直觉得Array的indexOf函数很好用,可惜微软的IE浏览到IE8都还不支持,只有自己拓展了,下面的代码我认为是比较的实现。
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;
}
}
这函数里的~~很有意思。~~是由两个~(按位“非”)运行符组成,发现实用性还是有的。
~~true; //1 Number
~~false; //0 Number
~~'123'; //123 Number
~~'0fs'; //0 Number
上面的测试代码可以告诉我们‘~~’对来对纯数字的String或布尔值转为数字很有用。以前写过这样的代码
[console.log, alert][!!document.all?1:0]('nootn.com简单其实不简单!');
现在可以这样写了
[console.log, alert][~~!!document.all]('nootn.com简单其实不简单!');
2 条评论 ▼
谢谢分享!!!
好资源 顶一个