Recently I was in a job interview, and someone made me a test:
var array = [1, 2, 3];
array[10] = 10;
alert(array.filter( n => n === undefined));
I was confident this was going to alert an array with 7x undefined, or something among those lines.
However, it outputs an empty array, as in an array of length 0.
For me this is perplexing. Can someone help me explain why this is happening ?
Deleted or uninitialized (on sparse arrays) items are not visited.
Array#forEach
Description
forEach()
executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).
var array = [1, 2, 3, , , , , , , , 10];
console.log(array.filter((n, i) => (console.log(i), n === undefined)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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