[英]how to get values for multidimensional array from user in node/javascript
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在 C 编程中从用户那里获取多维数组的值,我们可以使用两个 for 循环和 scanf 来获取值。当我在节点 javascript 尝试以类似方式尝试失败时
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')
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);
The error describes that arr[i]
is undefined
, which means that no properties can be set on it.该错误描述arr[i]
是undefined
,这意味着不能在其上设置任何属性。
Each dimension of the multidimensional array should be created in each iteration of the loop:多维数组的每个维度都应该在循环的每次迭代中创建:
for (let i = 0; i < 6; i++) {
// 👇 initialize the dimension as an empty array
arr[i] = new Array();
for (let j = 0; j < 6; j++) {
arr[i][j] = readlineSync.questionInt('')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.