Home > other >  how to get values for multidimensional array from user in node/javascript
how to get values for multidimensional array from user in node/javascript

Time:01-15

getting values for a multidimensional array from users in C programming, we can use two for loops and scanf to get values.When I tried that in similar way in node javascript attempt was failed

I have tried something like this:

var readlineSync = require('readline-sync')
var arr = new Array();

console.log('enter aray values');

for (let i = 0; i < 6; i  ){
    for (let j = 0; j < 6; j  ){
       
 arr[i][j] = readlineSync.questionInt('')
   
 }

}

console.log(arr);

and I got an error saying :

arr[i][j] = readlineSync.questionInt('')
                  ^
TypeError: Cannot set properties of undefined (setting '0')

CodePudding user response:

you can't set properties on undefined.

var readlineSync = require('readline-sync')
var arr = new Array();

console.log('enter aray values');

for (let i = 0; i < 6; i  ) {
    for (let j = 0; j < 6; j  ) {
        arr[i] = [];
        arr[i][j] = readlineSync.questionInt('')
    }
}

console.log(arr);

CodePudding user response:

The error describes that arr[i] is undefined, which means that no properties can be set on it.

Each dimension of the multidimensional array should be created in each iteration of the loop:

for (let i = 0; i < 6; i  ) {
    //            
  •  Tags:  
  • Related