1

I'm using https://js.do/ as a sandbox for simple scripts and document.write to print results. I'm working with multidimensional arrays, with code such as

var x = [];

x[1, 2] = 0;

However, I'm a little confused on what exactly document.write is printing.

On researching multidimensional arrays in JS, I found no mention of the notation used above, but rather x[1][2] was used in the examples found instead (ie. an array inside of an array).

I can't remember where I first came across the above way of using multidimensional arrays - perhaps someone could provide a link to enlighten me?

Shuri2060
  • 729
  • 6
  • 21

2 Answers2

3

x[1, 2] = 0; assigns 0 to index 2 of x, where comma operator , evaluates last value of 0, 2 expressions as an index of x at bracket notation

var x = [];

x[1, 2] = 0;

console.log(x[2] === 0);
guest271314
  • 1
  • 15
  • 104
  • 177
  • Oh wow - I'd mistakenly thought that was the correct notation, but it was completely wrong. Thankfully only started the multidimensional array part a while ago. It explains what I was getting from `document.write` as well – Shuri2060 Aug 11 '17 at 01:26
0

The syntax with the comma is incorrect, but apparently doesn't cause a syntax error. It is being interpreted by simply taking the last value, so the example x[1,2] = 0 is being views as x[2] = 0. That creates an array with 0 in the third position (index 2), [undefined,undefined,0]. As that gets written to the DOM, the undefined is ignored, but a comma is still added. So your output is ,,0.

dfat
  • 1