2017-04-20 26 views
0

我想建立一個關聯數組parentTds然而它不是我想要的方式工作。JavaScript關聯數組不工作的Jquery對象

var parentTds = {}; 
var index = 0; 
$.each(clone, function() { 
    var $currentItem = $(selectedActivities[index]); 
    var $currentItemTd = $currentItem.closest('td'); 
    console.log($currentItemTd.get(0)); 
    var borderLeft = 0; 
    console.log(parentTds[$currentItemTd.get(0)]); 
    console.log(parentTds[$currentItemTd]); 
    if (typeof parentTds[$currentItemTd.get(0)] === "undefined") { 
     console.log('NOT OK'); 
     borderLeft++; 
     parentTds[$currentItemTd.get(0)] = $currentItemTd; 
    } else { 
     console.log('OK'); 
    } 
    index++; 
}); 

由於某種原因parentTds[$currentItemTd.get(0)]始終返回存儲的第1個項目。我只是在第一次循環運行時得到NOT OK,而我應該得到NOT OK幾次。我懷疑問題本身就是parentTds[$currentItemTd.get(0)]

有什麼想法嗎?

+1

提示:JavaScript * object *(不是「關聯數組」)屬性名稱(鍵)始終是字符串。 '$ currentItemTd.get(0)'不是一個字符串,但是當你試圖用它作爲一個鍵時,它被強制轉換爲一個字符串。 – nnnnnn

+0

您能否提供一些關於'clone'和'selectedActivities'包含的解釋。此功能的目的是什麼,您是否試圖將父項的「td」元素添加到DOM中的對象中。一個對象只能有一個父項,所以該列表只能包含一個項目。除非你想把所有'td'都放在一張桌子上?這個問題需要更多的澄清你試圖達到的目標。 –

+0

@nnnnnn:你說的沒錯。我最終使用Arrays'[]'而不是關聯數組,並且完全像現在這樣工作。 –

回答

0

Javascript並不像PHP那樣寬容。當您使用此:

if (typeof parentTds[$currentItemTd.get(0)] === "undefined") { 

$currentItemTd.get(0)可能evaulated爲0,因此參考始終是parentTds[0]

在這種情況下我使用,打破了代碼塊,做這樣的事情:

var cig = $currentItemTd.get(0); 
if (typeof parentTds[cig] === "undefined") { 
相關問題