Reputation: 85
I want to get random names from the nameArray
and each time delete that element, so that in the end, I have got all names and the nameArray
is empty. Nothing displays in the console.
let i;
let nameArray = ['Chara','Lisette','Corine','Kevin','Carlee'];
while(i < nameArray.length){
let name = nameArray[ Math.floor( Math.random() * nameArray.length )];
console.log(name);
delete nameArray[i];
}
Upvotes: 0
Views: 365
Reputation: 821
i
is never initialized nor updated, so the while loop doesn't make too much sense.
You can try this instead:
let nameArray = ['Chara','Lisette','Corine','Kevin','Carlee'];
while(nameArray.length > 0) { // while the array is not empty
let i = Math.floor(Math.random() * nameArray.length); // pick a random element index
console.log(nameArray[i]); // print the element
nameArray.splice(i, 1); // remove the element from the array
}
Upvotes: 2