简体   繁体   English

为什么空数组上的indexOf不返回-1?

[英]Why does indexOf on an empty array does not return -1?

I am trying to check if an array contains a given value: 我试图检查数组是否包含给定值:

var arr = [];

if (arr.indexOf(2)) {
    console.log('yes');
}

Fiddle 小提琴

Why is the if condition always met, although arr does not contain a value of 2 ? 为什么始终满足if条件,尽管arr不包含值2 Shouldn't it return -1 and therefore nothing should be logged? 不应该返回-1 ,因此不记录任何内容?

Your condition should be: 你的病情应该是:

if (arr.indexOf(2) >= 0)

because in JavaScript, 0 is false when coalesced to a boolean, and any other number is considered true . 因为在JavaScript中,当合并为布尔值时0false ,而任何其他数字都被认为是true

Therefore... -1 is coalesced to true . 因此...... -1合并为true

 alert(!!-1) 

If you run this code in your browser's console, you'll see that it does return -1. 如果您在浏览器的控制台中运行此代码,您将看到它确实返回-1。 However, in a JavaScript if statement, -1 is truthy so the alert will execute. 但是,在JavaScript if语句中,-1是真实的,因此警报将执行。 As detailed in this excellent JavaScript equality table , there's only a very few values which will evaluate as false in an if statement: false , 0 , "" , null , undefined and NaN . 正如这个优秀的JavaScript相等表中所详述的那样,只有很少的值会在if语句中评估为false: false0""nullundefinedNaN

It does return -1 but -1 in Javascript is considered "truthy". 它确实返回-1但Javascript中的-1被认为是“truthy”。

Try this to see that it is indeed returning -1: 试试这个,看它确实返回-1:

var i = arr.indexOf(2);
console.log(i);

You need to explicitly compare for non-equality to -1 in your condition. 您需要在条件中明确地将非相等性与-1进行比较。

Here's an updated version of your jsfiddle: 这是你的jsfiddle的更新版本:
http://jsfiddle.net/bmj8y8bj/ http://jsfiddle.net/bmj8y8bj/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM