I am trying to do something like this – OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n OOOOOOOOOO n where a user would input a certain row from the array, and a certain column, and an X can be placed there instead of the zero. I have tried using a switch table, but I can not think of a more efficient way. Here is the code I have so far.
var allRows2 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows3 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows4 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows5 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows6 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows7 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows8 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows9 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var allRows10 = ["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"];
var userinr = prompt("Which row would you like to put the X in?");
var userinc = prompt("Which column would you like to put your piece in?");
switch(userin) {
case "1":
var therow = 1;
break;
case "2":
var therow = 2;
break;
case "3":
var therow = 3;
break;
case "4":
var therow = 4;
break;
case "5":
var therow = 5;
break;
case "6":
var therow = 6;
break;
case "7":
var therow = 7;
break;
}
I am unsure how to continue, any help would be appreciated:)
Advertisement
Answer
Instead of storing each row in an individual variable, store all the rows in nested arrays. Then reference the item and position with bracket notation:
var allRows = [["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"]]; const row = 2; const position = 5; allRows[row][position] = "X" console.log(JSON.stringify(allRows))
If you want to print the array without commas, you can use Array.join and set the delimiter to an empty string:
var allRows = [["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"],["O", "O", "O", "O", "O", "O", "O", "O", "O", "O"]];
const row = 2;
const position = 5;
allRows[row][position] = "X"
for(const row of allRows){
console.log(row.join(''))
}