samedi 14 février 2015

holes in arrays vs. undefined and the map function


I understand that map is not called on undefined indexes on arrays and I appreciate that an undefined index is different from an array index explicitly assigned the 'undefined' value (it is, isn't it?). Yet, how is one supposed to distinguish between holes in an array and undefined values?


The below code:


foo.js



var arr = [,,undefined,,,,3,,,4];
console.log("A hole the same as undefined? "+(arr[0]===undefined?"yes":"no"));
var _ignored = arr.map(function(x) {console.log("f called on ["+x+"]");});


... produces when running:



$ node foo.js
A hole the same as undefined? yes
f called on [undefined]
f called on [3]
f called on [4]


... similar results are to be had when replacing map with forEach.





Aucun commentaire:

Enregistrer un commentaire