0

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?

7
  • ele.push[q]=0; -> either ele[q]=0; or ele.push(0);. Same with M.push[p]=ele; Commented Mar 11, 2021 at 14:18
  • 1
    Actually after a second look M.push[p]=ele; shouldn't be done that way at all because you'll assign the same array to every index in M. The easiest thing is to make Array.from({length: n}, () => Array(n).fill(0)) Commented Mar 11, 2021 at 14:20
  • 1
    How to create a 2d array of zeroes in javascript? Commented Mar 11, 2021 at 14:21
  • Oops, guess I just forgot how .push works. :) My bad. Thanks Commented Mar 11, 2021 at 14:24
  • 1
    You say "ele always remains undefined". You're not returning it. That variable only exists while the function is running. Commented Mar 11, 2021 at 14:35

2 Answers 2

3

You can't use push like this Array.push[x]. if you use push on an array it always puts that item to the end of the array (https://www.w3schools.com/jsref/jsref_push.asp). so you can use:

ele.push(0);

OR

ele[q] = 0

Sign up to request clarification or add additional context in comments.

Comments

0
  1. create a non sparse Array of custom length
  2. map each array item (the undefined value) into

function squareMatrix(n, value) {
  return Array

    // creates a non sparse, thus iterable, array 
    // which features n-times the undefined value.
    .from({ length: n })

    // thus, one can map over each item.
    .map((item, idx) =>

      // creates a sparse array of custom length `n` which
      // immediately after gets filled with the custom `value`.
      Array(n).fill(value)
    );
}

console.log(
  'squareMatrix(2, 0) ...',
  squareMatrix(2, 0)
);
console.log(
  "squareMatrix(3, '👍🏻')",
  squareMatrix(3, '👍🏻')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.