Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.indexOf function on an array not working in IE7/8 using JavaScript

Can anyone tell me if IE 7 and IE 8 support the JavaScript .indexOf() method as I am receiving the error:

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

from the IE9 debug console (used under both IE7 and IE8 Browser mode).

For the below comment, the code using .indexOf() is as follows:

if(shirt_colour == 'black') {
    p_arr=['orange','red','green','yellow','bblue','rblue','pink','white','silver','gold'];
    if( p_arr.indexOf(print_colour) != -1 ) rtn = true;
}
like image 256
Gga Avatar asked Jul 18 '12 15:07

Gga


People also ask

Can you use indexOf for an array?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.

How do you find the index of an element in an array in JS?

JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.

How do you use indexOf in array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How does indexOf work in JavaScript?

The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring.


2 Answers

On IE<9 indexOf() it is not "well" implemented. Try to add this function on your code :

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

It will "replace" the original function, if not found in the ECMA-262 standard.

like image 191
markzzz Avatar answered Sep 23 '22 21:09

markzzz


Following code can be helpful.

function findIndexOf(findfrom, findthis) {
    for (i = 0; i < findfrom.length; i++) {
        if (findfrom[i] == findthis) {
            return i;
        }
    }
    return -1;
}
like image 25
Chandikumar Avatar answered Sep 21 '22 21:09

Chandikumar