Johnny
Johnny

Reputation: 107

Javascript IndexOf Queries

var fruits=["Apple", "Oranges", "Mutton", "Chicken"]

alert(fruits.indexOf("Mutton", 1));      // returns 2

alert("Blue Whale".indexOf("", 10));     // returns 10

Syntax

str.indexOf(searchValue[, fromIndex])

An optional [fromIndex] lets you specify the position in which to begin the search (default is 0, or search entire array):

Then why the below code returns 2:

 alert(fruits.indexOf("Mutton", 1));

I think it should start the search from the first index that is 'Oranges' and display the result as 1. But it is displaying Result 2.

Also

"Blue Whale".indexOf("", 10)

Here in "Blue Whale" string, the index value is upto 9. Then, why it is also accepting 10 and displaying the result as 10.

Upvotes: 0

Views: 140

Answers (5)

user1636522
user1636522

Reputation:

Consider the following sample :

var a = [1, 2, 3, 1, 2, 3];
a.indexOf(1); // 0
a.indexOf(1, 1 /* = skip index 0 */); // 3
a.indexOf(1, 2 /* = skip indexes 0 and 1 */); // 3

I want to ignore the first occurence :

a.indexOf(1, a.indexOf(1) + 1); // 3

Upvotes: 0

Rasmus Stougaard
Rasmus Stougaard

Reputation: 433

Its because you set the start position to 10 and search for "nothing".

Had your start position still been 10 and the string you searched for been example "e" it would return -1

Syntax

string.indexOf(searchvalue,start)

Upvotes: 0

MasNotsram
MasNotsram

Reputation: 2273

The indexOf optional parameter does not return the position of a unique element in the array relative to the starting point, it is simply used to only search for the element in the array after that starting point.

For example, if you had this:

var fruits=["Mutton", "Apple", "Oranges", "Mutton", "Chicken"]

then

 alert(fruits.indexOf("Mutton", 0)); //Alerts 0

would return 0 because Mutton is at index 0, however if you start the search from index 1 instead, it's already past Mutton so won't see it, and will instead find the first entry of Mutton after index 1, which is 3 now:

 alert(fruits.indexOf("Mutton", 3)); //Alerts 3

http://jsfiddle.net/zKrzu/

Upvotes: 0

Grundy
Grundy

Reputation: 13382

Syntax

str.indexOf(searchValue[, fromIndex])

so it start find from selected index but return index in collection, so index "Mutton" is 2, its returns

with case empty string returns string length

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Even if the search starts at position x, the value returned will be the index of the element from the start of the array

In the case of "Blue Whale".indexOf("", 10) there are 10 characters and you are searching for an empty string which is found after the last char that is why 10 is returned

Upvotes: 2

Related Questions