lastIndexOf and of methods for arrays and strings

  • 2021-01-25 07:09:48
  • OfStack

Array.prototype.lastIndexOf and String.prototype.lastIndexOf are very useful methods, but many people don't realize that they can actually pass two arguments, the second parameter determining the starting position of the search:

grammar


str.lastIndexOf(searchValue[, fromIndex])

The lastIndexOf() method returns the last occurrence of the specified value in the string in which the method was called, or -1 if it was not found. Look forward from the end of the string, starting at fromIndex.

parameter

1.searchValue
A string representing the value to be looked up.
2.fromIndex
Start the lookup at this position in the method string where the call was made. It could be any integer. The default value is str.length. If it is negative, it is considered to be 0. If fromIndex > str.length, then fromIndex is considered str.length.

Case sensitive

The lastIndexOf method is case sensitive. For example, the following expression returns -1:


"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1

The use of the lastIndexOf


// Create an array.
var ar = ["ab", "cd", "ef", "ab", "cd"];

//  To find the last 1 a CD The location of the 
document.write(ar.lastIndexOf("cd") + "<br/>");
//  The output : 4

//  From the positive 2 Search for the penultimate position 1 a CD The location of the 
document.write(ar.lastIndexOf("cd", 2) + "<br/>");
//  The output : 1

//  From the bottom of the first 3 At the end of the search 1 a ab The location of the 
document.write(ar.lastIndexOf("ab", -3) + "<br/>");
//  The output : 0

Similarly, String.lastIndexOf is used in a similar way


"canal".lastIndexOf("a") // returns 3
"canal".lastIndexOf("a",2) // returns 1
"canal".lastIndexOf("a",0) // returns -1  From the first 0 Go ahead, it doesn't exist 'a' To return to -1
"canal".lastIndexOf("x") // returns -1

IE8 implementation of lastIndexOf

However, Microsoft IE8 and the following does not support Array.lastIndexOf, compatible implementation is required. For reference:


if (!Array.prototype.lastIndexOf) {
 Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
 'use strict';

 if (this === void 0 || this === null) {
  throw new TypeError();
 }

 var n, k,
  t = Object(this),
  len = t.length >>> 0;
 if (len === 0) {
  return -1;
 }

 n = len - 1;
 if (arguments.length > 1) {
  n = Number(arguments[1]);
  if (n != n) {
  n = 0;
  }
  else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  n = (n > 0 || -1) * Math.floor(Math.abs(n));
  }
 }

 for (k = n >= 0
   ? Math.min(n, len - 1)
   : len - Math.abs(n); k >= 0; k--) {
  if (k in t && t[k] === searchElement) {
  return k;
  }
 }
 return -1;
 };
}

You can use ES5-Slim to make older browsers fully compatible with ES5 syntax.

Why should you avoid for in

Note that the for in syntax also enumerates the lastIndexOf methods after the Array.prototype method is appended to the Array.prototype method:


for (var idx in [1,3,5,7,9]) {
 console.log(idx)
}

>> 0 1 2 3 4 lastIndexOf

Instead, it should be implemented using for loop


for (var idx = 0; idx < [1,3,5,7,9].length; idx++) {
 console.log(idx)
}

This problem can be implemented using Object.defineProperty to avoid the enumeration of lastIndexOf methods for for:


Object.defineProperty(Array, "lastIndexOf", { enumerable: false })

However, most browsers that require a compatible implementation do not support the defineProperty approach at all. Also for in is much slower than for loop on most browsers, so for in should be avoided as much as possible. But how do you enumerate key for Object attributes? keys({a:1}) returns an array of keys.


Related articles: