简体   繁体   中英

confusion about lastIndexOf in javascript

 var a="bananas";
 a.lastIndexOf("a",1)  /// output is 1
 a.lastIndexOf("a",2)  /// output is 1
 a.lastIndexOf("a",4)  /// output is 3

Can anyone explain me how output is coming 1 for both the cases I know it is trying to matches from last end but I am unable to understand the logic from official doc

Please read the paragraph about Definition and Usage on W3Schools

The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

Note : The lastIndexOf() method is case sensitive!

Tip: Also look at the indexOf() method.


Syntax

string.indexOf( searchvalue, start )

Parameter Values

search ( Required ) The string to search for start

value ( Optional, default: 0 ) At which position to start the search


Your example:

var a = "bananas";
a.lastIndexOf("a",1)  // output is 1
a.lastIndexOf("a",4)  // output is 3

a.lastIndexOf("a",1) will search for the last 'a' in bananas whose index <= 1.

What this means is that it will return the last location of an a in 'ba'.

So a.lastIndexOf("a",4) will search for the last a in 'bana'.

It's indeed somehow confusing. But keep in mind that the value parameter will actually trim the string at the given position as the function will search backwards from that location.

lastIndexOf() search backwards so in your example, the counter would be as follows:

b a n a n a s
7 6 5 4 3 2 1
            ^

.lastIndexOf('a', 1) would be 1 because starting at position 1 and we see first 'a' at position 1

b a n a n a s
7 6 5 4 3 2 1
      ^
  3 2 1

.lastIndexOf('a', 4) would be 3 because starting at position 4, we see first 'a' at position 3.

The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

Definition and Usage

string.lastIndexOf(searchvalue, start)

Parameter

  • searchvalue (Required) The string to search for

  • start (Optional) The position where to start the search (searching backwards). If omitted, the default value is the length of the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM