How to print whole list in for loop?

  • A+

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

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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: