2016-03-22 38 views
1

我在這裏丟失了什麼?無法得到它爲什麼我的控制檯行爲有所不同取決於while循環是否存在?關於函數中數組的控制檯日誌行爲

function findPath(){ 
    var openArr = []; 
    var closeArr = []; 
    var morefun = {}; 
    var morefun1 = {}; 
    var morefun2 = {}; 
    morefun.f = 1; 
    morefun1.f = 2; 
    morefun2.f = 3; 
    openArr.push(morefun1); 
    openArr.push(morefun2); 
    openArr.push(morefun); 
    console.log(Array.isArray(openArr)); 
    console.log(openArr); 
    console.log(openArr.length); 

    while (openArr.length){ 
    var current = openArr.pop(); 
    closeArr.push(current); 
    } 
} 
findPath(); 

我可是從得到的console.log(openArr)

[Object, Object,Object] 
length: 0 // when while loop is there. 

並獲得

[Object, Object,Object] 
0:Object 
1:Object 
2:Object 
length:3 // without while loop 

它doesent似乎是Chrome設置爲我的Firefox控制檯唯一的事情顯示了類似的結果 - 當我點擊一個數組詳細我得到的長度:0與循環和長度:3 w/o。我是否錯過了執行順序?

+0

這是所有的代碼?無論哪種方式我都會得到相同的結果 – Wainage

+0

你會得到什麼結果? –

+0

對不起......我的壞。這可以解釋爲什麼。 http://stackoverflow.com/a/23392650/4602928 – Wainage

回答

2

當您向控制檯寫入內容時,它將創建一個字符串,該字符串表示當時的對象狀態。但是,它還存儲對實際對象的引用,這就是您在控制檯中呈現的內容。

展開該參考顯示它的實際狀態,因爲字符串在打印時顯示它的狀態爲。如果您想查看每個console.log的數組完整狀態,則可以將其轉換爲JSON。

console.log(JSON.stringify(openArr, null, 2)); 

例子:

var arr = [{ n: 1 }, { n: 2 }, { n: 3 }]; 
 
console.log(arr); // [Object, Object, Object] 
 
arr.pop(); 
 
// Expand the array and you'll only see 2 elements 
 

 
var arr2 = arr.slice(0); 
 
// To see the full state of the array, serialize it 
 
console.log(JSON.stringify(arr2, null, 2)); // [ { "n": 2 }, { "n": 3 } ] 
 
console.log(arr2); // [Object, Object] 
 
arr.pop(); 
 
// Expand the array and you'll only see 1 element

+0

哦,我明白了,tyvm。我以爲瘋了.. –

相關問題