const rndInt = Math.floor(Math.random() * 50);
const arr = [];
const input = document.getElementById('answer').value;
function displaySeq() {
var i = 0;
while (arr.length < 21) {
arr[i] = {
sequence: [],
answer,
guess: []
};
i++;
for (j=0; j < 7; j++) {
arr[i].sequence[0] = rndInt;
arr[i].sequence.push(rndInt + j)
}
}
console.log(arr);
}
I know that this error means that the variable does not have a value but I'm not sure what to do to resolve.
Another unrelated Question would be that my goal is that with every iteration a new random integer is the first element of each array. Right now it's the same random integer for each array. Is there a way to fix this?
Observation : You are incrementing i after creating the array object and trying to access the array object at i index.
In simple way, you are trying to access arr[i+1] as at there is only one element in arr at this point of time.
Resolution : Increment the index i++ after completion of for loop.
Demo :
const rndInt = Math.floor(Math.random() * 50);
const arr = [];
function displaySeq() {
var i = 0;
while (arr.length < 21) {
arr[i] = {
sequence: [],
answer: [],
guess: []
};
for (j = 0; j < 7; j++) {
arr[i].sequence[0] = rndInt;
arr[i].sequence.push(rndInt + j)
}
i++;
}
console.log(arr);
}
displaySeq();
You cannot access arr[0] when it is empty. So, first, you will have to push to the array and then call arr[0].
Also, you are incrementing i and then pushing into the array. So, initially, you are accessing arr[1] before defining arr[0].
Try this instead:
function displaySeq() {
var i = 0;
while (arr.length < 21) {
arr.push({
sequence: [],
answer,
guess: []
});
for (j=0; j < 7; j++) {
arr[i].sequence[0] = rndInt;
arr[i].sequence.push(rndInt + j)
}
i++;
}
console.log(arr);
}