有比使用2个for
循环和2个if
语句更好的方法吗?
的jsfiddle:
https://jsfiddle.net/bobbyrne01/bmnk9bLz/
代码:
var documentsInDatabase = [{
id: '1',
revision: '1'
}, {
id: '2',
revision: '1'
}, {
id: '3',
revision: '1'
}];
// incorrect revision of document with id of 1, and non-existent document of id 4
var requestedDocuments = [{
id: '1',
revision: '2'
}, {
id: '4',
revision: '1'
}];
var result = {
ids_not_found: [],
revision_mismatches: []
};
// 4 nested blocks deep
for (var i = 0; i < documentsInDatabase.length; i++) {
for (var j = 0; j < requestedDocuments.length; j++) {
if (documentsInDatabase[i].id === requestedDocuments[j].id) {
if (documentsInDatabase[i].revision !== requestedDocuments[j].revision) {
result.revision_mismatches.push(requestedDocuments[j].id);
}
requestedDocuments.splice(j, 1);
break;
}
}
}
for (var l = 0; l < requestedDocuments.length; l++) {
result.ids_not_found.push(requestedDocuments[l].id);
}
document.getElementById('container').innerHTML = JSON.stringify(result, null, 2);
答案 0 :(得分:1)
将documentsInDatabase
转储到id
为对象的对象中,如下所示:
var documentsInDatabaseObj = {};
for(var i = 0 ; i < documentsInDatabase.length ; i++){
var id = documentsInDatabase[i].id;
documentsInDatabaseObj[id] = documentsInDatabase[i];
}
现在循环requestedDocuments
for(var j = 0 ; j < requestedDocuments.length ; j++){
var wantedId = requestedDocuments[j].id;
if(!documentsInDatabaseObj.hasOwnProperty(wantedId)){
result.ids_not_found.push(wantedId);
} else if(documentsInDatabaseObj[wantedId].revision !== requestedDocuments[j].revision){
result.revision_mismatches.push(wantedId);
}
}