0

I'm trying to write a game in javascript, and I want to have an array of size 16 that I can update and return in different functions. Here's what I have so far, and why it isn't working.

function startgame(){
   var status = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
   console.log(status.length);
   return status;
}

var status = startgame();
console.log("status length now: "+ status.length);

As expected, the first log inside the function shows 16. However, the second one after the function call says "status length now: 31". The returned array is counting all the commas. How can I avoid this?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • (btw, writing `[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]` is probably better than using `new Array`) – evolutionxbox Mar 31 '21 at 15:37
  • 1
    You're doing this in the global scope, so you're changing `window.status`. Use `let status` or `const status` instead to avoid the property on `window`. – VLAZ Mar 31 '21 at 15:37
  • 1
    As a side note, you might want to replace `var status = new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)` with `const status = (new Array(16)).fill(0)` (it creates an array of length 16 and fills it with `0`s) – secan Mar 31 '21 at 15:40

0 Answers0