DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Array.indexOf Fix //JavaScript Function

  • submit to reddit
        Just an idiot fix to increase the number of my posts =b

//+ Jonas Raoni Soares Silva
[].indexOf || (Array.prototype.indexOf = function(v){
       for(var i = this.length; i-- && this[i] !== v;);
       return i;


var x = [0,1,2,3];



Snippets Manager replied on Sun, 2006/10/22 - 5:18pm

Clever code counting backwards to -1 and all - you have a small typo line: for(var i = this.length; i-- && this[i] !== v;); should be: for(var i = this.length; i-- && this[i] != v;); Thanks for saving me 5 minutes work - ain't google great. Regards, Topper

Snippets Manager replied on Mon, 2012/05/07 - 1:26pm

#1. Yeah, what I've done looks more like the lastIndexOf haha, thanks for the warning... But I won't change my code , I'm lazy \o/ #2. I'm against this kind of fix that I've made, your one is inside an object, that's good, but I don't like such ".js" full of codes that won't probably be used :D

Cristian Carlesso replied on Fri, 2006/08/25 - 10:46am

in there is a lot of fixes for other methods like the regex.replace(string,function), array.pop,array.push etc.. here: the list of fix

Snippets Manager replied on Mon, 2006/08/28 - 4:26pm

Clever code, but JS spec searches from the front of the array to the end, and takes an optional starting index parameter. [].indexOf || (Array.prototype.indexOf = function(v,n){ n = (n==null)?0:n; var m = this.length; for(var i = n; i < m; i++) if(this[i] == v) return i; return -1; }); example var x = [0,1,2,3,1]; alert(x.indexOf(1)); alert(x.indexOf(1,2)); alert(x.indexOf(3)); alert(x.indexOf(4));