确定是否存在所请求的文档,以及它们是否与所请求的修订号匹配

时间:2016-08-04 19:57:15

标签: javascript

有比使用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);

1 个答案:

答案 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);
    }
}