I am trying to write a simple "getRandomIndex" function to return a random and unused index number for a given array but I get "Maximum call stack size exceeded" error at let rndIdx = Math.floor(Math.random() * (arr.length - 0)) 0;
.
const arr = [81, 33, 45, 22, 97, 19, 60];
const usedIndexes = []; // I am trying to store used indexes here
function getRandomIndex() {
let rndIdx = Math.floor(Math.random() * (arr.length - 0)) 0;
if(usedIndexes.includes(rndIdx)) {
getRandomIndex();
return;
} else {
usedIndexes.push(rndIdx);
}
return rndIdx;
}
// if the array length is more than 10, I always get "call stack size exceed" error.
for(let i = 0; i < arr.length; i ) {
// I need to use all elements in the array eventually
console.log(getRandomIndex());
}
What I am missing?
CodePudding user response:
You must check that the length of the array allows for different unused numbers.
if (usedIndexes.length>=arr.length) {
return null
}
CodePudding user response:
You need to return
the output of getRandomIndex()
rather than calling it, dumping the output, then returning nothing (which gives you undefined
)
Fixed Code
const arr = [81, 33, 45, 22, 97, 19, 60];
const usedIndexes = []; // I am trying to store used indexes here
function getRandomIndex() {
let rndIdx = Math.floor(Math.random() * (arr.length - 0)) 0;
if(usedIndexes.includes(rndIdx)) {
// used to be
// - getRandomIndex();
// - return;
return getRandomIndex();
} else {
usedIndexes.push(rndIdx);
}
return rndIdx;
}
// if the array length is more than 10, I always get "call stack size exceed" error.
for(let i = 0; i < arr.length; i ) {
// I need to use all elements in the array eventually
console.log(getRandomIndex());
}
Output
0
2
4
3
1
6
5