2016-08-02 82 views
0

使用AngularJs,代碼片段的較大程序的部分:X = {}創建自發對象

var thePortList = $scope.ipPortList; // an array of objects 
... 
... 
console.log("before", $scope.ipPortList, thePortList); 
thePortList[i] = {}; 
console.log("after", $scope.ipPortList, thePortList); 

創建此輸出:

before [] [] 
after [2: Object] [2: Object] 

我不知道爲什麼。我可以期望在多線程程序中看到類似的內容,但不能用Javascript。

x = {}應該爲數組中的元素指定一個新的空對象。對?我對這種行爲感到困惑。任何人都可以點亮一下嗎?

在我的本地計算機和plunkr上的Chrome中進行了測試。

Plunkr這裏:

完全plunkr控制檯輸出:Plunker Link

Event tracked Multipane Show Preview Toolbar undefined undefined 
editor-0.11.1.js:2 URL visited /?p=preview 
VM631:29 portList [] 
VM631:34 processing 0 [] undefined 
VM631:39 skipping 0 
VM631:34 processing 1 [] undefined 
VM631:39 skipping 1 
VM631:34 processing 2 [] undefined 
VM631:45 before [] [] 
VM631:47 after [2: Object] [2: Object] 
+3

您的預期產出是什麼?對象出現在'$ scope.ipPortList'和'thePortList'的* both *中是否存在問題?因爲這是正確的行爲,因爲它們都指向相同的數組。 – nnnnnn

+0

你能告訴我們你期望的行爲嗎 –

回答

1

這是一個正確的行爲,我想你誤會的日誌信息的含義。 您可以嘗試在控制檯這段代碼,看看結果:

var a=[]; 
a[2]={}; 
a 

output: [undefined × 2, Object__proto__: Object] 

控制檯日誌信息:在JavaScript中,如果你的值分配給數組項「[2對象]」省略2 undefined,即出他的長度,如果嘗試訪問從原始長度到索引的元素,則會得到未定義的值,這並不是因爲數組自動填充未定義,因爲這是訪問不存在的屬性的標準響應。實際上除了數組長度以外沒有任何變化。

+2

*「如果你給一個超出他的長度的數組項賦值,undefined將自動完成,直到項索引」* - JS不會創建值爲undefined的元素'填補這個空白。也就是說,從未有過值的缺失元素與明確賦予值「未定義」的元素之間存在差異。 (但控制檯確實讓你知道缺少多少元素。) – nnnnnn

+0

@nnnnnn一個有趣的證明是,Array(2).forEach(i => console.log(i))''和'[undefined,undefined ] .forEach(i => console.log(i))'產生不同的輸出。一個是空數組,其長度設置爲2,另一個是一個數組,其中有2個實際未定義的數組 –

+0

@nnnnnn是對的,我已經更正了答案。 – jarvanJiang