Pages

Javascript Array lastIndexOf() Method

4/7/14

Description:

Javascript array lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting atfromIndex.

Syntax:

array.lastIndexOf(searchElement[, fromIndex]);
Here is the detail of parameters:
  • searchElement : Element to locate in the array.
  • fromIndex : The index at which to start searching backwards. Defaults to the array's length, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, the whole array will be searched. If negative, it is taken as the offset from the end of the array.

Return Value:

Returns index of the found element from the last.

Compatibility:

This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work you need to add following code at the top of your script:
if (!Array.prototype.lastIndexOf)
{
  Array.prototype.lastIndexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]);
    if (isNaN(from))
    {
      from = len - 1;
    }
    else
    {
      from = (from < 0)
           ? Math.ceil(from)
           : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

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

Example:

<html>
<head>
<title>JavaScript Array lastIndexOf Method</title>
</head>
<body>
<script type="text/javascript">
if (!Array.prototype.lastIndexOf)
{
  Array.prototype.lastIndexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]);
    if (isNaN(from))
    {
      from = len - 1;
    }
    else
    {
      from = (from < 0)
           ? Math.ceil(from)
           : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

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

var index = [12, 5, 8, 130, 44].lastIndexOf(8);
document.write("index is : " + index ); 

var index = [12, 5, 8, 130, 44, 5].lastIndexOf(5);
document.write("<br />index is : " + index ); 
</script>
</body>
</html>
This will produce following result:
index is : 2
index is : 5  

No comments:

Post a Comment

Related Posts