我看到过很多代码将数组的索引与-1进行比较,例如:
if (index === -1)
这到底是做什么的?
我相信我们不能在负索引中存储值,至少不作为数组元素。 (我知道,作为数组的属性,我们确实可以这样做)。但是那么上述条件何时会返回true或false?
我看到过很多代码将数组的索引与-1进行比较,例如:
if (index === -1)
这到底是做什么的?
我相信我们不能在负索引中存储值,至少不作为数组元素。 (我知道,作为数组的属性,我们确实可以这样做)。但是那么上述条件何时会返回true或false?
考虑下面的代码
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var index = fruits.indexOf("Apple");
if(index != -1) {
alert ("Apple found at " + index)
} else {
alert ("Apple not in exists")
}
如果值存在,则数组的 indexOf 返回值的索引号(0 或 1 或 2),但如果该值不存在,则返回 -1。
谢谢!
index=== -1
成立时,为什么应该显示 Apple found at + index
? - Saurabh Tiwari
if ( ~str.indexOf(...) ) { console.log('Found!') }
。 - Salasar