我有一个这样的对象数组: 该代码应解释我要实现的目标,这可能/最聪明的方法是什么?
var allInfo = [
{id: "253", name: "Olaf"},
{id: "264", name: "Hermann"},
{id: "296", name: "Jamie"},
{id: "237", name: "Sophie"},
{id: "854", name: "Hanni"}
];
document.write(syncDB(allInfo, "545");
function syncDB(allInfo, idToCheck) {
if (idToCheck != "in any of this allInfo[].id)" {
allInfo.push(id: idToCheck, name: "");
return "just created a new index";
}
else if (idToCheck == "in any of this allInfo[].id") {
return "this id already exists";
}
};
答案 0 :(得分:1)
这是我修改syncDB函数的方式。
var allInfo = [{
id: "253",
name: "Olaf"
}, {
id: "264",
name: "Hermann"
}, {
id: "296",
name: "Jamie"
}, {
id: "237",
name: "Sophie"
}, {
id: "854",
name: "Hanni"
}];
document.write(syncDB(allInfo, "237") + "<br/>");
document.write(syncDB(allInfo, "545") + "<br/>");
function syncDB(allInfo, idToCheck) {
// Grab all ids first
const ids = allInfo.map(o => o.id);
if (!ids.includes(idToCheck)) {
allInfo.push({
id: idToCheck,
name: ""
});
return "just created a new index";
} else {
return "this id already exists";
}
};