最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does indexOf on an empty array does not return -1? - Stack Overflow

programmeradmin0浏览0评论

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? Shouldn't it return -1 and therefore nothing should be logged?

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? Shouldn't it return -1 and therefore nothing should be logged?

Share Improve this question asked Mar 14, 2015 at 21:41 SvenSven 13.3k29 gold badges97 silver badges156 bronze badges 1
  • In JavaScript Boolean(-1) === true, so Boolean([].indexof(2)) === true, but Boolean([2].indexOf(2)) === false. – David Foerster Commented Mar 14, 2015 at 21:48
Add a ment  | 

3 Answers 3

Reset to default 4

If you run this code in your browser's console, you'll see that it does return -1. However, in a JavaScript if statement, -1 is truthy so the alert will execute. 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.

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.

Therefore... -1 is coalesced to true.

alert(!!-1)

It does return -1 but -1 in Javascript is considered "truthy".

Try this to see that it is indeed returning -1:

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

You need to explicitly pare for non-equality to -1 in your condition.

Here's an updated version of your jsfiddle:
http://jsfiddle/bmj8y8bj/

发布评论

评论列表(0)

  1. 暂无评论