0
How to declare and getting input from the user using two dimensional array in JavaScript?!?
arrays
3 Answers
+ 2
Technically speaking, JavaScript does not have a two-dimentional array.
But you can create an array of arrays and it works pratically the same.
You can declare it like this:
var items = [
[1, 2],
[3, 4],
[5, 6]
];
access its members like this:
console.log(items[0][0]); // outputs 1
console.log(items[2][0]); // outputs 5
One way to get input from users would be:
var items = [];
var rows = parseInt(prompt('How many rows', '3'));
var cols = parseInt(prompt('How many columns', '2'));
var default = 1
var value;
for(var i = 0; i < rows; i++){
items.push([]);
for(var j = 0; j < cols; j++, default++){
value = parseInt(prompt('row ' +(i+1)+' col '+(j+1)+' = ', default));
items[i].push(value);
}
}
+ 1
what do you mean? you want fill a 2d array with user input? if yes you get user input, parse it in some format and fill the array
+ 1
Hi KroW
Great Answer from @Ulisses just small thing to add:
For ES 6 on wards you can use "for val of" to iterate your array like this
// iterate two dimentional array ES6 onwards
for (let val1 of arr3x4) {
for (let val of val1) {
console.log(val);
}
}