简体   繁体   English

(为什么)设置`array [NaN]`无效?

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

I was reading an article about javascript PRNGs , and I came across something that surprised me: 我正在阅读有关javascript PRNG的文章 ,发现了一些令我惊讶的东西:

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

a is now [] and no exception is thrown — the write to the array simply vanishes. a是现在[]和不会引发异常-写入到阵列简单地消失。 Try it out in your browser console if you don't believe me. 如果您不相信我,请在浏览器控制台中尝试一下。

I didn't believe him, so I tried it out in my browser console (Firefox 47): 我不相信他,因此我在浏览器控制台(Firefox 47)中进行了尝试:

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

» a
← Array [  ]
» b
← NaN

There are several curious things going on here, but in particular, I'm trying to understand why the statement a[b++] = 1 doesn't [appear to] do anything. 这里发生了几件奇怪的事情,但是特别是,我试图理解为什么a[b++] = 1语句没有[似乎]做任何事情。

There is a lot of stuff happening there. 那里发生了很多事情。

  1. The code does something - it assigns the value 1 to the a[NaN] . 该代码执行某些操作-将值1分配给a[NaN] And as soon as JS objects can only have string properties - the NaN is implicitly casted to a string, so in fact you have assigned 1 to a["NaN"] or a.NaN . 并尽快JS对象只能有字符串属性-在NaN是隐式浇铸为字符串,所以其实你已经指派1a["NaN"]a.NaN

  2. The console object is not standardised, so you cannot expect anything particular from it. console对象尚未标准化,因此您不能期望它有任何特殊之处。 The current implementation in FF though iterates through the array indexes. FF中的当前实现虽然遍历数组索引。 "NaN" is not an array index, since it's not even numerical, so there is nothing shown in the console. "NaN"不是数组索引,因为它甚至都不是数字索引,因此控制台中未显示任何内容。

 var a = new Array(); var b; a[b++] = 1; console.log(a[NaN], a["NaN"], a.NaN); 

Taking it from the top: 从顶部开始:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM