An explanation of the LastIndexOf () method of arrays and strings in JavaScript using the basics

Source: Internet
Author: User
Tags abs

Array.prototype.lastIndexOf and String.prototype.lastIndexOf are very useful methods, but many people do not know that it can actually pass two parameters, and the second parameter determines 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 that called the method, or 1 if it is not found. Look forward from the back of the string, starting at Fromindex.

Parameters

1.searchValue
A string that represents the value being searched for.
2.fromIndex
Start the lookup from this location where the method string is called. can be any integer. The default value is Str.length. If negative, it is treated as 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 LastIndexOf

Create an array.
var ar = ["AB", "CD", "EF", "AB", "CD"];

Find the location of the last CD
document.write (Ar.lastindexof ("CD") + "<br/>");
Output: 4

//from the second position of positive number, search the position of the penultimate CD
document.write (Ar.lastindexof ("CD", 2) + "<br/>");
Output: 1

//From the penultimate search to the last ab position
document.write (ar.lastindexof ("AB",-3) + "<br/>");
Output: 0

Similarly, the use of String.LastIndexOf is similar

"Canal". LastIndexOf ("a")//returns 3
"Canal". LastIndexOf ("A", 2)//returns 1
"Canal". LastIndexOf ("A", 0)// Returns-1 from the No. 0, there is no ' a ', return-1
"Canal". LastIndexOf ("x")//Returns-1

IE8 realization of LastIndexOf

However, Microsoft's IE8 and its following do not support Array.lastindexof, the need for a compatible implementation. can refer to:

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 to avoid using the for in

It should be noted, however, that the for-in syntax also enumerates the LastIndexOf methods after the Array.prototype method is attached:

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

>> 0 1 2 3 4 LastIndexOf

Instead, you should use a for loop to implement

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 LastIndexOf method in the for-in:

Object.defineproperty (Array, "LastIndexOf", {enumerable:false})

However, browsers that generally require a compatible implementation do not support the DefineProperty method at all. And in most browsers for in is much slower than for loop, so you should try to avoid using for in. But how do you enumerate the key of the object property? Use Object.keys ({a:1}) to return an array of keys.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.