Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

javascript - What does 0 mean in indexOf?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...