9

Based on http://ie.microsoft.com/testdrive/HTML5/ECMAScript5Array/Default.html, I thought IE9 supports indexOf in array but the following breaks. Any idea why?

<script type="text/javascript">
    var a = [59, 20, 75, 22, 20, 11, 63, 29, 15, 77]; 
    var result = a.indexOf(32);//
    document.write(result);
</script>

Error message as below:

SCRIPT438: Object doesn't support property or method 'indexOf' 

test.php, line 9 character 1

tanyehzheng
  • 2,201
  • 1
  • 20
  • 33
  • It works for me but if you really need it there is a shim at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility. – pimvdb Oct 17 '11 at 10:07

3 Answers3

12

Are you sure your page is running in IE9 mode? Check in dev tools (F12). If you have old DOCTYPE you might be seeing your page in IE8/7 mode, so indexOf is not supported. If you are running in IE9 mode then it works just fine.

Aux
  • 440
  • 3
  • 10
  • 2
    I suggest using HTML5 doctype: it works everywhere and is future-proof (at least I like to think that). – Aux Oct 17 '11 at 10:14
  • I'm not sure if that would switch older IEs into standards compliant mode, but then again maybe it's time to stop caring. – Tomalak Oct 17 '11 at 10:18
  • Older IEs do not support indexOf for Array, so you should have a shim for them anyways. That includes not only older IEs, but also older versions of other browsers - they are also used nowadays. – Aux Oct 17 '11 at 10:21
  • No, they don't. But they will render the page in quirks mode, which might have other adverse side-effects. The MDC has a nice "Compatibility" section on how to add `indexOf()` to browsers that do not natively support it: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf – Tomalak Oct 17 '11 at 11:26
0

your code looks right and this compatibility table shows that IE9 should support indexOf() and checks your actual browser for compatibility.

try to open it and take a look at your result. maybe you're running you IE in compatibility mode for IE7/8 or something else.

this jsfiddle works in my IE9 - please try that, too.

oezi
  • 51,017
  • 10
  • 98
  • 115
-2

It might help if you declare the array explicitly:

var a = new Array(1,2,3);
a.indexOf(2);
Fabian
  • 4,160
  • 20
  • 32
  • doesn't make a difference, this works: http://jsfiddle.net/byFYT/ - the problem is the compatibility mode. – oezi Oct 17 '11 at 10:14
  • Ok, good. Sometimes the IE in all versions needs a special treatment. Glad this was not the case here. – Fabian Oct 17 '11 at 10:16
  • 1
    The new Array(...) and new Object() syntax is bad practice. Always use array and object literals instead. (i.e. var x = { foo: 'bar' } instead of: var x = new Object(); x.foo = 'bar'; and [1, 2, 3] instead of new Array(1, 2, 3);) – DanilF Feb 14 '13 at 15:47