(为什么)设置 array[NaN] 什么都不做?

(Why) does setting `array[NaN]` do nothing?

我正在阅读 an article about javascript PRNGs,我遇到了一些让我感到惊讶的事情:

var a = new Array();
var b;
a[b++] = 1;

a is now [] and no exception is thrown — the write to the array simply vanishes. Try it out in your browser console if you don’t believe me.

我不相信他,所以我在我的浏览器控制台 (Firefox 47) 中试了一下:

» var a = new Array();
» var b;
» a[b++] = 1

» a
← Array [  ]
» b
← NaN

这里发生了一些奇怪的事情,但特别是,我试图理解为什么语句 a[b++] = 1 没有 [似乎] 做任何事情。

那里发生了很多事情。

  1. 代码做了一些事情 - 它将值 1 分配给 a[NaN]。一旦 JS 对象只能具有字符串属性 - NaN 被隐式转换为字符串,因此实际上您已将 1 分配给 a["NaN"]a.NaN.

  2. console 对象未标准化,因此您不能期望它有任何特殊之处。 FF 中的当前实现虽然遍历数组索引。 "NaN" 不是数组索引,因为它甚至不是数字,所以控制台中没有显示任何内容。

var a = new Array();
var b;
a[b++] = 1;

console.log(a[NaN], a["NaN"], a.NaN);

从顶部开始:

var a = new Array();
// 'a' is now an empty array, plain ol' boring empty array, could have been 
// written as a = [];
var b;
// 'b' have no value and is 'undefined'. 'console.log(b); // undefined'
a[b++] = 1;
// Lets break the above statement down into pieces:
  b++       // Increment b by one, undefined + 1 === NaN
a[   ]      // Use NaN as a property for our array 'a'
       = 1; // Assign 1 to that property
// Ok? So what happened why does 'a' still look empty?
console.log(a); // []
// The way your console with show you an array is by printing the numeric keys
// in it, and looking at the length, eg:
// var q = [];
// q.length = 1;
// console.log(q); // [undefined x 1]

// With 'a' in our case there is no numeric keys in it so [] is printed.
// So did our value dissapear?
// No. It is there:
console.log('NaN' in a); // true
// And:
for (var prop in a) console.log(prop); // NaN

// Why is this even a feature? 
// Arrays are extending Objects so they have the same properties as em.
console.log(a instanceof Object); // true
console.log(a instanceof Array); // true