2016-06-11 67 views
0

我讀an article about javascript PRNGs,和我遇到的東西,讓我感到驚訝傳來:(爲什麼)設置`array [NaN]`什麼也不做?

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

a現在是[]並不會引發任何異常 - 寫入到陣列簡單地消失。如果你不相信我,請在瀏覽器控制檯中試用。

我不相信他,所以我想它在我的瀏覽器控制檯(火狐47):

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

» a 
← Array [ ] 
» b 
← NaN 

有一些稀奇古怪的事情怎麼回事,但特別是,我試圖理解爲什麼陳述a[b++] = 1不[似乎]做任何事情。

+4

它確實 - 它分配了'1'到'一個[NaN的]'。嘗試訪問'一個[NaN]'看看它在那裏。這也是一條很滑的道路 - 你期望從一個不標準化的主機對象(「控制檯」不是)。那麼,你怎麼知道你看到的是*預期*還是沒有? – zerkms

回答

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 
+0

'縮進b,一個,undefined + 1 === NaN'?爲什麼「縮進」? 'b ++'與'b + 1'不一樣。 – melpomene

+0

我想我想說:'給b添加一個。 – andlrc

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);

+0

@Mgetz注意:它首先被轉換爲字符串,所以'NaN'不等於它本身並不重要。 「作爲一個數組對象的索引」---它不是,根據標準的索引只能是數字的(有更多的限制,但在這種情況下這些都沒有關係)。 – zerkms