Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

While I am writing some JavaScript, I came across a new code "indexOf". After read another post I thought its behaviour is as shown below but it seems not true. Can someone kindly give me an explanation about "indexOf", please?

false = -1; true = 0 and more?

I have tried to change -1 to 0 and more but then nothing happens. Just to have a better understanding about jquery/indexOf.

what I have now,

$(this).closest(row)[td_word.indexOf(keyword) !== -1 ? 'show' : 'hide']();

it search for match(es) of "keyword" from "td_word", if it is not false (!== -1, thus true) display:visible;, if it is not true (false) display:hide;.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
295 views
Welcome To Ask or Share your Answers For Others

1 Answer

array.indexOf(element) returns the index of the element in the array. Read the official documentation as well.

It was designed to return -1 when the element doesn't exist, because 0 would mean that the element is in the 0th index (1st element).

Examples :

var array = ['a','b','c','d','e'];

array.indexOf('a') //0
array.indexOf('c') //2
array.indexOf('f') //-1, because it doesn't exist in array

From what I understand in your wording, I think that you think that indexOf is used to check if a certain element exists in an array. That is just a "side-effect" of indexOf but its actual usage is getting the index of an element in the array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...