0

I found these methods, indexOf() apparently doesn't work for internet explorer 8

There are a lot of options, I want to know which one is like the defacto or what I should opt to use for best results.

Also, if the result is undefined, how do I use that as a value do I simply use it as a string like "undefined" or is it null?

array.find() 
array.findIndex()
array.indexOf("string");

In this example of replacing a string within an array knowing the index, they use indexOf, should I be concerned of incompatibility?

var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}
  • possible duplicate of [How to find if an array contains a specific string in JavaScript/jQuery?](http://stackoverflow.com/questions/6116474/how-to-find-if-an-array-contains-a-specific-string-in-javascript-jquery) – Shridhar Mar 02 '15 at 16:45
  • Have a look on this http://stackoverflow.com/questions/6116474/how-to-find-if-an-array-contains-a-specific-string-in-javascript-jquery – Shridhar Mar 02 '15 at 16:48

1 Answers1

0

It's perfectly acceptable to use a polyfill for these types of things:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill

if (!Array.prototype.indexOf) {
    // paste polyfill here
}

You could also use methods provided by different libraries:

// jQuery
if ($.inArray("some_value", someArray) > -1) { ... }

// Underscore
if (_.contains(someArray, "some_value")) { ... }
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
  • those are reserved words? the array.prototype and thanks for your answers – killinitsincenam Mar 02 '15 at 17:06
  • I'm not sure about what you are asking about reserved words. `indexOf` is certainly reserved as of ECMA 5 - but IE8 does not implement ECMA 5 and therefor `indexOf` isn't really "reserved" in that browser. Polyfilling is a technique for bringing modern functionality to older browsers. There are hundreds of things you can polyfill - but I recommend only doing what you need. – Ryan Wheale Mar 02 '15 at 19:43
  • I was referring to array.prototype, I came across it on MDN and I wondered if that was only for that instance eg. the word prototype but you mentioned it too. – killinitsincenam Mar 02 '15 at 22:42
  • Ah, I see. `Array` (with a capital 'A') is the "constructor" object for javascript arrays. Creating an "instance" of the Array constructor is easy: `var my_array = []`, which is essentially the same as `var my_array = new Array()`. Javascript constructors have a special `prototype` property which is set of methods and properties which are inherited by each instance. Since `indexOf` is defined on `Array.prototype`, `my_array` can use that method: `my_array.indexOf(...);` – Ryan Wheale Mar 03 '15 at 17:07