What Is The Difference Between [undefined] And [,]?
Solution 1:
[,]
is a sparse array. It has a length of 1
, but no values (0 in [,] === false
). It can also be written as new Array(1)
.
[undefined]
is an array of length 1
with the value undefined
at index 0
.
When accessing the property "0
", both will return undefined
- the first because that property is not defined, the second because the value is "undefined". However, the arrays are different, and so is their output in the console.
Solution 2:
[,]
creates an array with length of 1 and no indices.
[undefined]
creates an array with length of 1 with undefined
value at index 0
.
Chrome's undefined × x
is for sparse arrays that don't have sequential indices:
var a = [];
a[8] = void 0; //set the 8th index to undefined, this will make the array's length to be 9 as specified. The array is sparse
console.log(a) //Logs undefined × 8, undefined, which means there are 8 missing indices and then a value `undefined`
If you were to use .forEach
on a sparse array, it skips the indices that don't exist.
a.forEach(function() {
console.log(true); //Only logs one true even though the array's length is 9
});
Where as if you do a normal .length
based loop:
for (var i = 0; i < a.length; ++i) {
console.log(true); //will of course log 9 times because it's only .length based
}
There is a gotcha if you expect .forEach
to behave the same as non-standard implementations.
new Array(50).forEach( function() {
//Not called, the array doesn't have any indices
});
$.each( new Array(50), function() {
//Typical custom implementation calls this 50 times
});
Solution 3:
Thats odd []
outputs just []
again for me on Chrome 21.
Anyway [a, b, c, ...]
is the array notation of Javascript so you are basically defining an array with no values.
However an ending ,
is acceptable to make array generation easier. So what Chrome is telling you is there is one undefined value in the array. See code for examples.
[,,]
> [undefined x2]
[1,2,]
> [1, 2]
[1,2,,]
> [1, 2, undefined × 1]
[1,2,,,]
> [1, 2, undefined × 2]
[1,2,,3,4,,,6]
> [1, 2, undefined × 1, 3, 4, undefined × 2, 6]
Solution 4:
It looks like it's just a shorthand way to display the repeated 'undefined' values. eg:
> [,,,]
[ undefined x 3 ]
But []
is not the same as [undefined]
at all. I'd double check that if I were you.
Post a Comment for "What Is The Difference Between [undefined] And [,]?"