I have numbers array, through my_number function I create a random numer, if it already exist in the array, I call the function again and create a new random number, if it is not in the array I send it to it through push.
Unfortunately it sems to send all numbers again and again until browser crashes.
How could I fix this.
Thanks for your help
var numbers = [1,2,3,4,5];
function mainFunction(){
function my_number(){
var randomNumber = Math.floor((Math.random()*7)+1);
for(let i=0; i<numbers.length; i++){
if(numbers[i] === randomNumber){
my_number();
}else{
numbers.push(randomNumber);
}
}
}
my_number();
}
mainFunction();
In my_number function, you have called my_number again inside for-loop and it is needed to call my_number function with the result of the for-loop.
So it is needed to get the result if the randomNumber has existed or not through for-loop and based on that, you need to decide to call the function again or not.
Preferred Way
const numbers = [1,2,3,4,5];
function mainFunction(){
function my_number(){
const randomNumber = Math.floor((Math.random()*7)+1);
const isExisted = numbers.some((item) => item === randomNumber);
if (isExisted) {
my_number();
} else {
numbers.push(randomNumber);
}
}
my_number();
}
mainFunction();
console.log(numbers);
Regarding your CodeBase.
const numbers = [1,2,3,4,5];
function mainFunction(){
function my_number(){
const randomNumber = Math.floor((Math.random()*7)+1);
let isExisted = false;
for (let index = 0; index < numbers.length; index ++) {
if (numbers[index] === randomNumber) {
isExisted = true;
break;
}
}
if (isExisted) {
my_number();
} else {
numbers.push(randomNumber);
}
}
my_number();
}
mainFunction();
console.log(numbers);
There are quite a few problems with the code.
i should be numbers[i] to compare the array element instead of the index.numbers.push(randomNumber) should be done outside the for loop because it would otherwise only check if randomNumber matches the first element and ignores the rest.my_number in the for loop, you need a return statement to prevent the loop from continuing after detecting failure.var numbers = [1,2,3,4,5];
function my_number() {
var randomNumber = Math.floor((Math.random() * 7) + 1);
for(let i = 0; i < numbers.length; i++){
if (numbers[i] === randomNumber){
my_number();
return;
}
}
numbers.push(randomNumber);
}
my_number();
console.log(numbers);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With