Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print whole list in for loop?

Tags:

javascript

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);
like image 874
Steve Avatar asked May 03 '18 07:05

Steve


People also ask

How do I print a list of elements in a for loop?

Printing a list in python can be done is following ways: Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one using a for loop, this is the standard practice of doing it.

How do I iterate through an entire list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.

How do you print a full list in Python?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.

Can you for loop a list?

Using Python for loop to iterate over a list. In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration. Inside the body of the loop, you can manipulate each list element individually.


1 Answers

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

like image 79
Sam Ho Avatar answered Oct 02 '22 08:10

Sam Ho