Was writing a function that takes in an array of numbers and returns true and the index if there is a missing number or false if there are no missing numbers. I Just noticed something about arrays that confuses me.
An array like
[,1,2,3,4]
will print
[undefined,1,2,3,4]
The array starts with a comma, Output makes sense to me
But why does
[1,2,3,4,] // Notice that the array ends with a comma
[1,2,3,4]
I would have assumed the output would be [1,2,3,4,undefined]
.
Does anyone know why this is so?
The trailing comma ("elision") is ignored:
If an element is elided at the end of an array, that element does not contribute to the length of the Array.
http://www.ecma-international.org/ecma-262/7.0/#sec-array-initializer
Note that only one comma is stipped on the right, so this [1,2,,]
will be rendered as [1,2,undefined]
.
In Javascript arrays are just objects with a special length
property, and an array initializer like
['a', 'b', 'c']
is a shortcut for
{
"0": 'a',
"1": 'b',
"2": 'c',
"length": 3
}
An elision makes the initializer skip the next index and increases the overall length
, so this
['a', 'b', , 'c']
becomes this:
{
"0": 'a',
"1": 'b',
"3": 'c'
"length": 4
}
and two trailing elisions
['a', 'b', 'c', , ]
become
{
"0": 'a',
"1": 'b',
"2": 'c',
"length": 4
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With