开发者

truthiness of strings vs. keys

Today I tried shortening an if statement like this:

if (fruit == "apple" || type == "pear" || type == "orange"){

to this:

if (fruit in ["apple", "pear", "orange"]){

It doesn't work. Jonathan Snook has a different solution here where he essentially uses a map like this, which does work:

if(fruit in {"apple":"", "pear":"", "orange":""}){

Why does that work and my simple array doesn't, when usually in Javascript an object's presence makes that object return true? Is a string a different type of object than a key? I thought the string's presence in my array would return true as well.

y = "Stackoverflow";
y && console.log('y is true') // y returns true, so console logs the message

I interpreted my original solution as "if the value of variable fruit is in this array." That's clearly not the case. Does it instead say "if the variable fruit itself is in this array?" No, because this doesn't work either开发者_高级运维:

if (fruit in [fruit, "apple", "pear", "orange"]){

So what is Snook's version with the key=>value map asking that's correct? My best guess is, "if a key under the name of the value of variable fruit in this map returns true?"


x in y returns true if the object y has a property with name x (so yes, your guess is correct).

Arrays are objects too. The properties of an array are the indexes, which are numerical . This works:

if(0 in ["apple", "pear", "orange"])

because the array has an element at index 0. This array is similar (but not the same!) to this object:

{0: "apple", 1: "pear", 2:"orange"}

(of course an array has further properties like length, push, slice, etc)

In your object example ({"apple":"", "pear":"", "orange":""}), apple, pear etc. are the properties of the object, not the values of properties.

How to find out whether an element is contained in an array is described in How do I check if an array includes an object in JavaScript? .


†: Strictly speaking, every property is a string, so even if you use numbers (as it is the case with arrays), they are converted to strings.


To check if a value is within an array, use indexOf:

if (["apple", "pear", "orange"].indexOf(fruit) != -1){

Note: IE < 9 does not support indexOf on arrays, but you can add support easily.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜