7

I just want to practice Javascript, so I try this easy code. In my expected that the output should be whole list.

When I use this code I only can get the output is

[5, 9, 17, 14, 4, 19, 11, 8, 13, 10, 18, 15, 16, 20]

I did not know what happened on it, and where was

[1,0,2,3,6,7,12...]

var li = [5,9,17,14,1,0,4,19,11,6,8,13,10,2,18,15,16,3,12,7,20]
var length = li.length;
var x = [];
for(var i = 0; i < length; i++){
  if(!(li[i]in x)){
    x.push(li[i]);
  };
}
console.log(x);
Bill P
  • 3,622
  • 10
  • 20
  • 32
Steve
  • 73
  • 7

3 Answers3

8

the condition checking if(!(li[i]in x)){ is not correct. in check if keys(index) exist in the array .

Change to if(!x.includes(li[i])){

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
Sam Ho
  • 206
  • 1
  • 4
  • See [this thread](https://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value) for browser support info and alternative methods – Oneiros May 03 '18 at 07:52
3

From Javascript if in x I got

JavaScript does have an in operator, but it tests for keys and not values.

So you don't get those values because you check for the key -> 0, 1, 2, 3, etc. and at the position of e.g. item 1 in your list the 1st key is already used.

In other words what the if in your specific case actually does is if(x.length < li[i]).

Just to clarify if(x.length < li[i]) is not the same as !(li[i]in x) in every case!

To print the whole list use includes for your if. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Johannes
  • 958
  • 9
  • 14
  • *In other words what your if actually does is if(x.length < li[i]){*. **This is not true**. `x.length < li[i]` is **not the same** as `!(li[i]in x)` – Adelin May 03 '18 at 08:35
  • @Adelin, of course you are right the `==` is not right here! And you are also right with `x.length < li[i]` is not the same as `!(li[i]in x)`, i never said that! But in @Steve's specific case `x.length < li[i]` has the same effect as `!(li[i]in x)` so he may got a better explanation for the `in` operator – Johannes May 03 '18 at 10:33
0

If you want to print each one at a line use console.log(li[I]); insidr the for loop, or remove everything and use console.log[li]; to print the whole array all together

Rainbow
  • 6,772
  • 3
  • 11
  • 28