0

following the snippet bellow, why an array with one position is not working properly when using IN operation?

You can see that with 2 item the operation works fine.

  • Why this is happening?
  • What's the work around?

// helper function
function showResult(result) {
  document.querySelector('#result').innerHTML += result+'<br/>';
}

var a = ["1"]
var b = "1"

showResult(b in a);
//false

var a = ["1","2"]
var b = "1"

showResult(b in a);
//true
<div id="result"></div>
Alvaro Silvino
  • 9,441
  • 12
  • 52
  • 80
  • 1
    While we're on the topic, you should read about `for..in` with [this question](http://stackoverflow.com/q/500504/5743988) if you haven't before. It's a common pitfall. – 4castle Aug 11 '16 at 19:30
  • @4castle thanks for poiting out the question! I will read it now! – Alvaro Silvino Aug 11 '16 at 19:33

3 Answers3

5

That's not what in is for. in is not for searching an array for an element. It's for searching an object for a key.

Example:

var x = {a: 1, b: 2};
console.log('a' in x); // true

Your 2nd example works because the array (object) a contains a key called 1.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
3

The in operator checks if an object has a key, not a value. Your second case returns true because any array with two elements has keys '0' and '1'. It doesn't matter that '1' also happens to be a value in that array; '1' in ['foo', 'bar'] is also true.

To test if an element is in an array, you should use Array.prototype.indexOf or in modern engines Array.prototype.includes. You can use the polyfill from either of those links to get support for that method in all engines:

// Most engines (IE 9+)
showResult( a.indexOf( b ) >= 0 );

// Modern engines only:
showResult( a.includes( b ) );
Paul
  • 139,544
  • 27
  • 275
  • 264
1

The first result is false because a does not have an index 1, while the second version of a has that index.

The in operator is not about affirming values, but properties (keys).

The confusion is maybe because CoffeeScript does use in for searching values. See here how it translates that into an indexOf

trincot
  • 317,000
  • 35
  • 244
  • 286