javascript - jQuery inArray() 的返回值

标签 javascript jquery

我正在阅读jQuery's documentation about the inArray method我无法真正理解一句话的含义。如果该元素不在数组中,则该方法返回 -1,否则返回 0,其内容如下:

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

我无法理解 JavaScript 将 0 视为松散等于 false 的事实与检查方法的返回值的需要有什么关系。即使 JavaScript 不能以这种方式工作,我是否也需要这样做?

最佳答案

这基本上意味着您需要像这样编写测试:

if ($.inArray(value, array) > -1) {
    // the element is inside the array
}

而不是:

if ($.inArray(value, array)) {
    // the element is inside the array
}

不应该使用第二个构造的原因是,如果该值是数组的第一个元素,则 inArray 函数将返回 0(因为这是数组的第一个元素的索引)数组),如文档中所述 0 表示 false:

if (0) {
    // this will never run
}

关于javascript - jQuery inArray() 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10479152/

相关文章:

javascript - 如何在可过滤的投资组合链接中使用特殊字符?

javascript - Typeof 仅显示精确结果

javascript - Yelp 鼠标跟踪机制

javascript - Owl Carousel - 幻灯片顺序,直接跳到选中的幻灯片

javascript - 在 jQuery 中执行 new Date() 时如何设置正确的格式?

javascript - CSS基本的Multipanel图布局D3.js

javascript - 尝试使用当前时间与关闭时间javascript进行倒计时

javascript - 通过 JQuery/JS 使用其他组合框选择更新组合框

javascript - Django 模板 - ajax 响应 - 如何?

javascript - MapReduce 还是普通查询? (每个 map 发出几个)