0

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];
 }
1
  • 1
    You made an infinite loop! This statement (i < nameArray.length) is always correct. Commented Jan 12, 2021 at 11:01

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.