skip to Main Content

I’m cleaning up a game of tic-tac-toe I made a while back because I’m bored but I ran into a problem. The items are different because whenever I use .push or .splice on them it adds "" around the numbers. Can anyone help me fix this?

const winningCombos = ["123", "456", "789"];
const myCombos = [];
myCombos.splice(0, 0, "2");
console.log(myCombos);
myCombos.splice(0, 0, "1");
console.log(myCombos);
myCombos.push("3");
console.log(myCombos);
if (winningCombos[0] === myCombos[0]) {
  console.log("Success")
} else {
  console.log("Fail")
}

All I want it to do is it to end with the console saying Success and the numbers being equal to 123. Can anybody help me?

2

Answers


  1. If you want myCombos to be an array similar to winningCombos, you shouldn’t be splicing and pushing onto it. You should concatenate to the individual strings in the array.

    const winningCombos = ["123", "456", "789"];
    const myCombos = ["", "", ""];
    myCombos[0] = "2";
    console.log(myCombos);
    myCombos[0] = "1" + myCombos[0];
    console.log(myCombos);
    myCombos[0] += "3"
    console.log(myCombos);
    if (winningCombos[0] === myCombos[0]) {
      console.log("Success")
    } else {
      console.log("Fail")
    }

    As you can see, with strings it’s not so easy to insert a new character in a specific place, because they’re immutable. It would be easier if you used a 2-dimensional array.

    const winningCombos = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ];
    const myCombos = [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]
    ];
    myCombos[0][1] = 2;
    console.log(myCombos);
    myCombos[0][0] = 1;
    console.log(myCombos);
    myCombos[0][2] = 3;
    console.log(myCombos);
    if (arrays_equal(winningCombos[0], myCombos[0])) {
      console.log("Success")
    } else {
      console.log("Fail")
    }
    
    function arrays_equal(a1, a2) {
      return a1.length == a2.length && a1.every((el, i) => el == a2[i]);
    }
    Login or Signup to reply.
  2. in the mind of a simple admirer of George Boole

    const player = (()=>
      {
      let binPos = 0;  
      const winningCombos =  // change this values in binary numbers
          ['123', '456', '789','159' , '753'] 
          .map(s=>[...s].reduce((n,x)=> n |=  1 << --x , 0))
      , add_Pos =p=> { binPos |= 1 << --p; }
      , is_Win  =_=> winningCombos.some(win => (win === (win & binPos)))
          ;
      return { add_Pos, is_Win }
      })();
    
    // Let play!    
    
    player.add_Pos(2);
    player.add_Pos(3);
    player.add_Pos(1);
    
    console.log( player.is_Win() ) // true
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search