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. So the following will output: "is NOT in array"

如果对象在数组中,它将返回0,但是在Javascript中0是错误的。下面将输出"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.

但这使得代码不可读。特别是对于那些不知道这个函数的人。他们会期待jQuery。inArray(“test”,myarray)在数组中显示“test”。

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.

我的问题是,为什么要这样做?我真的不喜欢这样。但这样做一定有很好的理由。

15 个解决方案

#1


524

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.

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

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

因此,要检查数组中是否有项,请使用:

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

更多相关文章

  1. 禁用焦点上的锚点()元素上的灰色边框
  2. 在jQuery中使用部分ID查找元素?(复制)
  3. 使用数字作为javascript对象元素的名称
  4. 使用类似$(“。someClass”)的JQuery确定元素集合是否可见
  5. 创建一个未排序的数组,其中包含重复元素和唯一元素的总和
  6. jQuery在元素内部检测mousedown,然后在元素外部进行mouseup
  7. 如何在angularjs代码中单元测试jquery元素
  8. jquery1.9+获取append后的动态元素
  9. Jquery | 基础 | 慕课网 | 元素选择器

随机推荐

  1. Android 7.1.2(Android N) Android系统启
  2. Android安装
  3. Android 控件常用属性
  4. JAVA & Android 系统环境变量配置
  5. Android 7.1 去掉桌面上的谷歌搜索框
  6. Android实时获得周围wifi信息(SSID,强度等)
  7. android 塔防游戏汇总 及android 游戏开
  8. 【Android】【Framework】Android_Framew
  9. android图片切换ImageSwichter的动画切换
  10. Android Shape 详解