Site Navigation

Sunday, December 28, 2008

bug 433 - no Array.indexOf( value ) in IE6 IE7 or IE8

Issue: #433
Affects: IE6, IE7, IE8

As one of the basic JavaScript data types Arrays are great for storing lists of data. You can sort them, push, pop, splice & join them!

However in IE you can't find the index of a value in your array using the native .indexOf( value ) method. Likewise the .lastIndexOf( value ) method won't work in IE either.


Example:

<script type="text/javascript">
var foo = [];
foo.push('aaa');
foo.push('bbb');
foo.push('ccc');
foo.push('ddd');
alert(foo.indexOf('ccc'));
</script>


In good modern browsers this will alert "2" but in IE you will just get an error.


Known Workarounds: One. You'll need to prototype your own. (thanks to jcartledge for pointing out that we missed posting the workaround)


<script type="text/javascript">
if(isIE){
Array.prototype.indexOf = function(k){
var len = this.length;
for(i=0;i<len;i++){
if(this[i] == k){
return i;
}
}
return -1;
};
}

if(isIE){
Array.prototype.lastIndexOf = function(k){
var len = this.length;
for(i=len-1;i>-1;i--){
if(this[i] == k){
return i;
}
}
return -1;
};
}
</script>



Related Issues: (bug 181), (bug 253).

Bug/Site Feedback |
Submit a bug