New to JavaScript! I am trying to create a function that generates 3 unique integers from 0-9 and stores in Array. However, I keep getting undefined array error.
CodePudding user response:
1) You're declared solutionArray
as an array so you can't use solutionArray(i)
, It means you are solutionArray
is a function and you are invoking it with argument i
. You can use .push
method to push elements in an array.
solutionArray.push(r);
2) You should return value from the function createSolution
if you are using it outside of it.
return solutionArray;
function createSolution() {
//solution array
const solutionArray = [];
for (let i = 0; i < 3; i ) {
let r = Math.floor(Math.random() * 10);
solutionArray.push(r);
}
return solutionArray;
}
console.log(createSolution());
CodePudding user response:
solutionArray
is an empty array. You are pushing a randomly generated number to the item in the array at the loop index. However, since it's an empty array, that item doesn't exist so there's nothing to push to.
You should instead be pushing directly to solutionArray
.
Therefore, replace this line:
solutionArray[i].push(r);
with:
solutionArray.push(r)
Your function should then be:
function createSolution() {
const solutionArray = [];
for (let i = 0; i < 3; i ) {
let r = Math.floor(Math.random() * 10);
solutionArray.push(r);
}
return solutionArray;
}