2

Possible Duplicate:
IE9 array does not support indexOf

My Code:

var arrFruits = ['apple', 'banana', 'carrot', 'dates'];
var position = arrFruits.indexOf( 'carrot' );
position > -1 && arrFruits.splice( position, 1 );
alert( arrFruits );

The above code is displaying the result as apple, banana, dates in Chrome. But it is not working in IE9.

Community
  • 1
  • 1
Earth
  • 3,477
  • 6
  • 37
  • 78

3 Answers3

6

It may be issue of .indexOf not being supported. It basically is supported in IE9 unless some malicious doctype is triggering it to render page in IE7/8 mode. Than Array.indexOf method is not supported.

I suggest using HTML5 doctype for example (<!DOCTYPE html>) to make sure IE9 is rendering correctly.

user1894004
  • 116
  • 2
  • I agree. Similar post [here](http://stackoverflow.com/questions/7792195/ie9-array-does-not-support-indexof). – tobias86 Dec 11 '12 at 08:30
2

till IE8 it doesn't have .indexOf method , you can add it like this, if you are using IE9 check for compatibility mode

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}
Community
  • 1
  • 1
Buzz
  • 6,030
  • 4
  • 33
  • 47
  • IE9 does support array.indexOf ? – adeneo Dec 11 '12 at 08:27
  • IE9 does support it. You just need to make sure the page is running in IE9 mode. Old doc types might cause it to run in IE7/8 mode. See this [SO question](http://stackoverflow.com/questions/7792195/ie9-array-does-not-support-indexof) for more info : – tobias86 Dec 11 '12 at 08:30
0

What is this line for

position > -1 && arrFruits.splice( position, 1 );

It evaluateto either true or false and then you don't do anything with it.that's probably causing a syntax error in IE, which the more forgiving Javascript engines on chrome and Firefox are ignoring.

Maybe you meant to make an if statement?

 if(position > -1) {
     arrFruits.splice( position, 1 ); 
}
just.another.programmer
  • 8,579
  • 8
  • 51
  • 90