Basic knowledge about the lastIndexOf () method of arrays and strings in JavaScript

Source: Internet
Author: User
This article describes how to use the lastIndexOf () method of arrays and strings in JavaScript. This article mentions IE8 compatibility and forin usage. For more information, see Array. prototype. lastIndexOf and String. prototype. lastIndexOf is a very practical method, but many people do not know that it can actually pass two parameters, the second parameter determines the start position of the Search:

Syntax

str.lastIndexOf(searchValue[, fromIndex])

The lastIndexOf () method returns the position where the specified value is located at the end of the string that calls the method. If no value is found,-1 is returned. Start from the back of the string and start from fromIndex.

Parameters

1. searchValue
A string that indicates the value to be searched.
2. fromIndex
Start from the position where the method string is called. Can be any integer. The default value is str. length. If it is a negative value, it is regarded as 0. If fromIndex> str. length, 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

LastIndexOf usage

// Create an array. var ar = ["AB", "cd", "ef", "AB", "cd"]; // locate the position document of the last CD. write (ar. lastIndexOf ("cd") +"
"); // Output: 4 // from the second position of the positive number, search for the position document. write (ar. lastIndexOf (" CD ", 2) +"
"); // Output: 1 // search for the last AB position from the last to the third: document. write (ar. lastIndexOf (" AB ",-3) +"
"); // 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 searches forward from 0th. If 'A' does not exist,-1 "canal" is returned ". lastIndexOf ("x") // returns-1

IE8 Implementation of lastIndexOf

However, Microsoft's IE8 and below do not support Array. lastIndexOf and must be compatible. Refer:

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

However, after attaching a method to Array. prototype, the for in syntax also enumerates the lastIndexOf method:

for (var idx in [1,3,5,7,9]) { console.log(idx)}>> 0 1 2 3 4 lastIndexOf

Instead, we should use 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 cited by for in:

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

However, browsers that require compatibility do not support the defineProperty method at all. In most browsers, for in is much slower than for loop, so we should avoid using for in as much as possible. But how do I enumerate the keys of Object attributes? Use Object. keys ({a: 1}) to return the array about 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.