Some usage that I find a bit tricky is
2 in [1, 3, 5]
for (var i in [1, 3, 5]) { ... }
str = "hello";
for (var i in str) { ... }
the first one is true (I might have immediately said 2 in [1, 3, 5] is false), and the second line loops through 0, 1, 2 instead of 1, 3, 5, and the last part loops through 0 to 4, instead of 'h', 'e', 'l', 'l', 'o'. Right now I am just using: whenever seeing in for array, or for-in loop for array, immediately think about index instead. Otherwise, is there a way or usage pattern that we can use to avoid this pitfall?
Yes, it’s called “do not use
infor arrays”. It tests if an object has a certain key – so you cannot properly use it on arrays.You also shouldn’t use
for(var x in something)unless you want to iterate over the properties ofsomething.To check if a value is contained in an array use
~arr.indexOf(value)– orarr.IndexOf(value) != -1if you want it more verbose.To iterate over the elements in an array use
for(var i = 0; i < arr.length; i++)