I am writing a program in JavaScript where you input a number n and it returns an array M that is a list of length 'n' and each element of the list is a different list ele that is also length n and has every element equal to zero. This is my function:
var zeros=function(n){
var M=[];
var ele=[];
for (var q=0; q<n; q++){
ele.push[q]=0;
}
for (var p=0; p<n; p++){
M.push[p]=ele;
}
return M;
};
My problem is that ele always remains undefined no matter how I try to change it. Can anyone tell me why this is happening and how to fix it?
ele.push[q]=0;-> eitherele[q]=0;orele.push(0);. Same withM.push[p]=ele;M.push[p]=ele;shouldn't be done that way at all because you'll assign the same array to every index inM. The easiest thing is to makeArray.from({length: n}, () => Array(n).fill(0)).pushworks. :) My bad. Thankselealways remains undefined". You're not returning it. That variable only exists while the function is running.