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];
}
Liam
30k28 gold badges145 silver badges206 bronze badges
1 Answer 1
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
}
answered Jan 12, 2021 at 10:48
Syco
8212 gold badges17 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
(i < nameArray.length)is always correct.