2

Using Javascript in Firefox, Safari and Chrome (didn't try IE), the following strange behavior happens:

data = new Array(1,3,5,7,9);

data[1,7,3] = 88;

alert( data );     //  displays: 1,3,5,88,9

So apparently the value at index [3] has been changed (other tests show that it actually has changed data[3]).

The second command does not generate an error. It does not even generate a warning in NetBeans, nor an error when displayed in a browser.

I explored this a bit further. It appears that :

data[1,7,null,NaN,4,3]  

also gets interpreted as data[3] - this also works with other values than 3.
The last value in the list is used and the rest are ignored.

Does this behavior have some sort of meaning or purpose, or is it just an unexpected fault in the parser?

I was unable to find any documentation or explanation of this behavior/syntax.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164

1 Answers1

0

You're using the comma operator.

<expr1>, <expr2>, <expr3>, ...

is an expression that evaluates each expression from left to right, and returns the value of the last one. So 1,7,3 evaluates to 3. So

data[1,7,3] = 88;

is equivalent to:

data[3] = 88;
Barmar
  • 596,455
  • 48
  • 393
  • 495