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

时间:2016-06-11 10:49:01

标签: javascript arrays nan

我正在阅读an article about javascript PRNGs,我发现了令我惊讶的事情:

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

a现在是[]并且没有抛出任何异常 - 对数组的写操作就会消失。如果您不相信我,请在浏览器控制台中试用。

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

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

» a
← Array [  ]
» b
← NaN

这里有几件奇怪的事情,但特别是,我试图理解为什么声明a[b++] = 1没有[似乎]做任何事情。

2 个答案:

答案 0 :(得分:1)

那里发生了很多事情。

  1. 代码执行某些操作 - 它将值[1] "Sepal_2010_.Length" "Sepal_2010_.Width" "Petal_2010_.Length" "Petal_2010_.Width" "Species" 分配给1。只要JS对象只能有字符串属性 - a[NaN]被隐式地转换为字符串,所以实际上您已将NaN分配给1a["NaN"]。< / p>

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

  3. "NaN"

答案 1 :(得分:0)

从顶部开始:

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