保持数组中的对象的主表,在添加新对象之前检查数组是否存在
问题描述:
下面的代码不能按预期工作。它从不检查主列表中的服务器。难道我做错了什么?保持数组中的对象的主表,在添加新对象之前检查数组是否存在
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...
}
]
答
尝试测试数组长度。
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.");
}
}
我会这样做,但我会处理服务器阵列中的很多对象,并且我需要找到一个具有相同ID的对象,因为它们都是唯一的。 – uplusion23
好的......你需要检查一个特定的对象是否在数组中...... –
你应该展示你的数组是如何构造的更具体的答案......; –