2016-07-26 93 views
0

下面的代碼不能按預期工作。它從不檢查主列表中的服務器。難道我做錯了什麼?保持數組中的對象的主表,在添加新對象之前檢查數組是否存在

var servers = []; 
$.serverlist.addServers = function(jsonData) { 
for (var server in servers) { 
    if (server["ID"] == jsonData["ID"]) { 
     // server exists, dont add, just update 
    } else { 
     //server doesnt exist, just add it 
    } 
} 

jsonData我收到的格式,像這樣:

{ "ID": 1, "something else": "Value", "another key": "Key Val" } 

因此,當它進入數組,數組狀態(如果有多個加)

[ 
0: 
    { 
    "ID":1, 
    "something else": "Value", 
    "another key": "Key Val" 
    } 
    1: 
    { 
    "ID":2,etc... 
    } 
] 

回答

0

嘗試測試數組長度。

if(servers.length > 0){ 
    // Server exist! 
    console.log("Append!"); 
}else{ 
    // Doesn't... 
    console.log("Create the array."); 
} 

編輯

對於一個特定的對象,這應該這樣做:

if(servers.indexOf(jsonData["ID"]) != -1){ 
    // Data is in array 
    console.log("It's there."); 
}else{ 
    // Doesn't... 
    console.log("It's not there."); 
} 



第二編輯

我瘋了它應該看起來像一個CodePen
但是我不確定你的數據是什麼......當你使用控制檯登錄時,它看起來像DOM對象格式。
我認爲這是一個json或一個對象不同...

我做了我的例子基於對象數組。 看看CodePen控制檯。

var servers = [ 
    { 
    "ID":1, 
    "something else": "Value", 
    "another key": "Key Val" 
    }, 
    { 
    "ID":2, 
    "something else": "another Value", 
    "another key": "another Key Val" 
    }, 
    { 
    "ID":3, 
    "something else": "Boring Value", 
    "another key": "Interesting!" 
    }, 
    { 
    "ID":4, 
    "something else": "arrggg.", 
    "another key": "Yeah!" 
    } 
]; 

for(i=0;i<servers.length;i++){ 
    var temp = servers[i]; 
    if (temp.ID== 3){ 
    console.log("Found!"); 
    break;     // Exits the loop when found ID = 3 
    }else{ 
    console.log("NOT fount yet... Still checking."); 
    } 
} 
+0

我會這樣做,但我會處理服務器陣列中的很多對象,並且我需要找到一個具有相同ID的對象,因爲它們都是唯一的。 – uplusion23

+0

好的......你需要檢查一個特定的對象是否在數組中...... –

+0

你應該展示你的數組是如何構造的更具體的答案......; –

相關問題