首页 > 解决方案 > How to print whole list in for loop?

问题描述

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

标签: javascript

解决方案


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


推荐阅读