我正在阅读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/