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);

9
  • What do you want to achieve ? Commented May 3, 2018 at 7:45
  • [5,9,17,14,1,0,4,19,11,6,8,13,10,2,18,15,16,3,12,7,20] Commented May 3, 2018 at 7:45
  • 3
    all you need just simply console.log(li) Commented May 3, 2018 at 7:46
  • This is your input data. Commented May 3, 2018 at 7:46
  • 1
    x is an array, so when you say something in array it treats array as an object. 1 in x is true because x has property 1, which is index 1, that's why 1 don't get pushed in x Commented May 3, 2018 at 7:47

3 Answers 3

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])){

Sign up to request clarification or add additional context in comments.

1 Comment

See this thread for browser support info and alternative methods
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

2 Comments

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, 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
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.