2012-04-03 83 views
1

所以我有兩個非常大的多維數組(4000+)。我得到第一個數組作爲來自服務器的響應,我必須爲每個這些數組元素創建dom節點。一旦這個過程完成後,我必須發送另一個請求,我會得到另一個元素列表,這將成爲第一個列表的一個子集,基於第二個列表,我必須修改第一個列表中的一些元素(並反映這些變化DOM也是如此)。這個過程需要很長時間才能完成,是否有任何方法可以在沒有兩個for循環的情況下完成此操作?或者更快的比較?Large arrays&javascript comparison

方案

現實世界的例子是如下,在一個特定的區域(ARR1)考慮一組人 。在DOM中,這將被表示爲 CheckBox - Name現在考慮一羣已經與 特定疫苗(arr2)一起施用的人,現在arr2具有應該檢查複選框的元素的列表。整個清單(arr1的dom代表)必須以 的成本顯示。

數組是類型

[ ["index", "name", "age"],............. ["4000-index", "4000-name", "4000-age"]] 

下面是一個僞代碼的..

//First request, get the response (resp) and Create DOM elements accordingly 
for(var i=0, iLen=resp.length; i<iLen; i++) 
{ 
    // Checkbox and <span id='entry-"+resp[i][0]+"'>resp[i][1]</span> 
} 
// At a later stage in the code... 
//Request server for the second list get the response (resp) 
arr2 = resp // Second Array 

// Walk through the dom, get the list of span elements and store their ids in an array arr1 
for(var i=0, iLen=arr1.length; i<iLen; i++) 
{ 
    for(var j=0, jLen= arr2.length; j<jLen; j++) 
    { 
    if(+arr2[j][0] === +arr1[i][0]) 
    { 
     //checkbox attr = 'checked' 
    } 
    } 
} 
+1

你有一些示例代碼 - 也許一個例子數據提供器?會更容易幫助:-) – santa 2012-04-03 09:03:41

+3

也許你應該重新思考服務器發送給客戶端的內容。由於2個列表是相關的,爲什麼有2個查詢? – mpm 2012-04-03 09:06:22

+0

@camus&santa:爲了便於理解,我更新了我的問題。這兩個查詢是因爲這些列表維護在不同的數據庫中。因此。 – 2012-04-03 09:11:16

回答

2

如果在第二組數據,您收到作爲一個對象具有以下發結構,你可以得到一些非常好的性能提升。

var subset = { 
    anID:{ 
     bcg: true, 
     someOtherProp: false, 
     //and so on 
    } 
} 

然後,所有你需要修改DOM元素 -

for (var id in subset){ 
    //do whatever needs to be done 
}