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
209 views
in Technique[技术] by (71.8m points)

javascript - jQuery.inArray(),如何正确使用它?(jQuery.inArray(), how to use it right?)

First time I work with jQuery.inArray() and it acts kinda strange.

(第一次使用jQuery.inArray() ,它的行为有点奇怪。)

If the object is in the array, it will return 0, but 0 is false in Javascript.

(如果对象在数组中,它将返回0,但是Javascript中的0为false。)

So the following will output: "is NOT in array"

(因此,将输出以下内容: “不在数组中”)

var myarray = [];
myarray.push("test");

if(jQuery.inArray("test", myarray)) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}

I will have to change the if statement to:

(我将不得不将if语句更改为:)

if(jQuery.inArray("test", myarray)==0)

But this makes the code unreadable.

(但这会使代码不可读。)

Especially for someone who doesn't know this function.

(特别是对于不了解此功能的人。)

They will expect that jQuery.inArray("test", myarray) gives true when "test" is in the array.

(他们期望当“ test”在数组中时,jQuery.inArray(“ test”,myarray)为true。)

So my question is, why is it done this way?

(所以我的问题是,为什么要这样做呢?)

I realy dislike this.

(我真的不喜欢这个。)

But there must be a good reason to do it like that.

(但是一定有充分的理由这样做。)

  ask by nbar translate from so

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

1 Reply

0 votes
by (71.8m points)

inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array.

(inArray返回数组中元素的索引,而不是指示该项目是否存在于数组中的布尔值。)

If the element was not found, -1 will be returned.

(如果找不到该元素,则将返回-1 。)

So, to check if an item is in the array, use:

(因此,要检查项目是否在数组中,请使用:)

if(jQuery.inArray("test", myarray) !== -1)

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

1.4m articles

1.4m replys

5 comments

57.0k users

...