Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0 in [1, 2] == true, why?

Tags:

javascript

Excerpt from my JavaScript console:

> 0 in [1, 2]
true

Why?

like image 712
Felix Avatar asked Mar 08 '10 13:03

Felix


People also ask

Why use 0 and 1 instead of true and false?

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

Does the integer 0 == false?

When converting to bool, the following values are considered false : the boolean false itself. the integer 0 (zero) the floats 0.0 and -0.0 (zero)

Is 0 == false in Python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true.

Is 0 true or false in boolean?

Treating integers as boolean values Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.


1 Answers

Because "in" returns true if the specified property/index is available in the object. [1, 2] is an array, and has a object at the 0 index. Hence, 0 in [1, 2], and 1 in [1, 2]. But !(2 in [1, 2]).

Edit: For what you probably intended, David Dorward's comment below is very useful. If you (somewhat perversely) want to stick with 'in', you could use an object literal

x = {1: true, 2: true};

This should allow 1 in x && 2 in x && !(0 in x) etc. But really, just use indexOf.

like image 121
Adam Wright Avatar answered Oct 21 '22 03:10

Adam Wright