javascript - (Why) does setting `array[NaN]` do nothing? -
i reading an article javascript prngs, , came across surprised me:
var = new array(); var b; a[b++] = 1;
a
[]
, no exception thrown — the write array vanishes. try out in browser console if don’t believe me.
i didn't believe him, tried out in browser console (firefox 47):
» var = new array(); » var b; » a[b++] = 1 » ← array [ ] » b ← nan
there several curious things going on here, in particular, i'm trying understand why statement a[b++] = 1
doesn't [appear to] anything.
taking top:
var = new array(); // 'a' empty array, plain ol' boring empty array, have been // written = []; var b; // 'b' have no value , 'undefined'. 'console.log(b); // undefined' a[b++] = 1; // lets break above statement down pieces: b++ // increment b one, undefined + 1 === nan a[ ] // use nan property our array 'a' = 1; // assign 1 property // ok? happened why 'a' still empty? console.log(a); // [] // way console show array printing numeric keys // in it, , looking @ length, eg: // var q = []; // q.length = 1; // console.log(q); // [undefined x 1] // 'a' in our case there no numeric keys in [] printed. // did our value dissapear? // no. there: console.log('nan' in a); // true // and: (var prop in a) console.log(prop); // nan // why feature? // arrays extending objects have same properties em. console.log(a instanceof object); // true console.log(a instanceof array); // true
Comments
Post a Comment