Never been to DZone Snippets before?

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

Array.indexOf fix //JavaScript Function (See related posts)

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

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


example

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

alert(x.indexOf(2));
alert(x.indexOf(4));

Comments on this post

boothby posts on Aug 28, 2006 at 17:52
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));
kentaromiura posts on Aug 29, 2006 at 13:47
in http://www.devpro.it/JSL/JSLOpenSource.js
there is a lot of fixes for other methods
like the
regex.replace(string,function), array.pop,array.push etc..

here: http://www.devpro.it/JSL/ the list of fix

jonasraoni posts on Sep 02, 2006 at 04:12
#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
Topper posts on Oct 22, 2006 at 18:21
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

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts