jQuery.inArray(),如何正确使用它? [英] jQuery.inArray(), how to use it right?

查看:101
本文介绍了jQuery.inArray(),如何正确使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次使用 jQuery.inArray()并且它有点奇怪。

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

如果对象在数组中,它将返回0,但在Javascript中0为false。因此,以下内容将输出:不在数组中

If the object is in the array, it will return 0, but 0 is false in Javascript. 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");
}

我必须将if语句更改为:

I will have to change the if statement to:

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

但这会使代码难以理解。特别是对于不了解这个功能的人。当test在数组中时,他们会期望jQuery.inArray(test,myarray)给出true。

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.

所以我的问题是,为什么要这样做办法?我真的不喜欢这个。但必须有一个很好的理由这样做。

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.

推荐答案

inArray 返回数组中元素的索引,而不是指示数组中是否存在该项的布尔值。如果找不到该元素,将返回 -1

inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.

因此,检查项目是否在数组,使用:

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

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

这篇关于jQuery.inArray(),如何正确使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆