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];
 }
Liam
30k28 gold badges145 silver badges206 bronze badges
asked Jan 12, 2021 at 10:39
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
}
answered Jan 12, 2021 at 10:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.