我有一個nodes_object
陣列,其具有以下種結構:Javascript:檢查元素是否在二維數組中的快速方法?
nodes_object = {
1: {
source: '001',
name: 'A',
target: '004',
name: 'B'
},
2: {
source: '003',
name: 'C',
target: '001',
name: 'A'
},
}
然後,我也有一個數組sorted
其被以下列方式構造:
sorted = {
1: {
val: '001',
count: '100'
},
2: {
val: '003',
count: '80'
}
我需要創建將通過nodes_object
重申一個函數,檢查source
和target
是否都包含在sorted
val
參數之一中,如果有,請繼續。
到目前爲止,我想出了下面的函數,它首先通過nodes_object
重申,然後通過sorted
重申,看看是否有任何的元素是在它存在,但我不知道是否有一個更快和更有效的方法來做到這一點?
謝謝!
for (var i = 0; i < nodes_object.length; i++) {
var sourcein = null;
var targetin = null;
for (var j = 0; j < sorted.length; j++) {
if (sorted[j].val == nodes_object[i][0]) {
sourcein = 1;
}
if (sorted[j].val == nodes_object[i][2]) {
targetin = 1;
}
}
if ((sourcein) && (targetin)) {
// Perform the function
}
}
這些都是對象,而不是數組。 – Barmar 2014-12-27 14:59:41
@Barmar不確定它們是否真的存在,或者它是否只是用於問題的奇怪符號。 – 2014-12-27 15:03:22
爲什麼你使用'null'和'1'而不是'false'和'true'? – nnnnnn 2014-12-27 15:35:04