javascript - Shorten JS if or statement -
this question has answer here:
is there anyway shorten in javascript: if (x == 1 || x == 2 || x == 3 || x == 4)
if (x == (1 || 2 || 3 || 4))
?
you can use use array.indexof
[1,2,3,4].indexof(x) !== -1
you can use objects kind of hash map:
//note: keys coerced strings // don't use method if looking object or if need // distinguish number 1 string "1" my_values = {1:true, 2:true, 3:true, 'foo':true} my_values.hasownproperty('foo')
by way, in cases should usi "===" strict equality operator instead of ==
operator. comparison using "==" may lots of complicated type coercion , can surprising results sometimes.
Comments
Post a Comment