0

I have the following code in Javascript:

var myArray = {"a":21600904, "b":21100999, "c":21602019, "d":21704354, "e":21602271, "f":21500123};
console.log(Object.values(myArray));
console.log(21600904 in Object.values(myArray));

And I get the following output:

[ 21600904, 21100999, 21602019, 21704354, 21602271, 21500123 ]
false

But this was not what I expected. What I understand is, 21600904 is inside Object.values(myArray) but 21600904 in Object.values(myArray) returns false instead of true.

What am I missing here? Why this code does not print true?

Berdan Akyürek
  • 212
  • 1
  • 14
  • 4
    `in` only checks the *keys*, not the values. Also, `myArray` is an *object* not an array. – VLAZ Nov 24 '20 at 10:47
  • 2
    did you mean `Object.values(myArray).includes (21600904)` – Bravo Nov 24 '20 at 10:47
  • 1
    `myArray = { ... }` -- your "array" is not an array but an object. An array is a collection of items indexed using integer numbers starting from `0`. – axiac Nov 24 '20 at 10:47
  • 2
    Read about [`for ... in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). It does not do what you think. The function you are looking for is [`Array.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – axiac Nov 24 '20 at 10:49
  • 1
    [in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) works for actual Objects, but it looks for the key, not the value. In other words, `"a" in myArray` should evaluate to `true`. –  Nov 24 '20 at 10:50
  • @axiac Yes, you are right, `myArray` is not an array. I named it this way because it is similar to the "associative array" structure. – Berdan Akyürek Nov 24 '20 at 10:55
  • @ChrisG here I am not using `in` for the object but for the list of values. I know something like `21600904 in myArray` should not return true since it is only checking the keys. But I use `21600904 in Object.values(myArray)` and Object.values(myArray) is an array as far as I understand. Why using `in` for an array does not give a correct result? – Berdan Akyürek Nov 24 '20 at 10:58
  • 1
    @BerdanAkyürek the keys of the array are `0`, `1`, `2`, etc. `21600904 in Object.values(myArray)` checks if the array has a key (read *index*) `21600904` in it. Since the array only has six element, then it doesn't have index which is after 21 million. – VLAZ Nov 24 '20 at 11:01
  • The "associative array" already has 3 other names in other languages and in theory: hash, map and dictionary. And the JavaScript objects. :-) – axiac Nov 24 '20 at 11:02
  • The keys of an array are 0, 1, 2 etc. so `123 in someArray` will be true **if** the array has at least 124 elements, and therefore a 123 *key*. –  Nov 24 '20 at 11:02

0 Answers0