0

How to declare and getting input from the user using two dimensional array in JavaScript?!?

arrays

29th Mar 2018, 8:19 AM
Code_Magician❀
Code_Magician❀ - avatar
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); } }
29th Mar 2018, 9:32 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 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
29th Mar 2018, 8:22 AM
KrOW
KrOW - avatar
+ 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); } }
29th Mar 2018, 10:05 AM
Mike Choy
Mike Choy - avatar