Large arrays&javascript comparison

问题描述:

所以我有两个非常大的多维数组(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

如果在第二组数据,您收到作为一个对象具有以下发结构,你可以得到一些非常好的性能提升。

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

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

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