这是我的建议:
// create an empty array
var objectiveDetails = [];
// set the current highestNumber to 0
objectiveDetails.highestNumber = 0;
// add a custom method to add an objectiveDetail
objectiveDetails.add = function(objectiveDetail) {
// if objectiveDetail is not given make an empty object
objectiveDetail = objectiveDetail ? objectiveDetail : {};
// if objectiveDetail.number is not given give it highestNumber+1
if (!objectiveDetail.number) {
objectiveDetail.number = objectiveDetails.highestNumber + 1;
}
// check if highestNumber is still the highest
if (objectiveDetail.number > objectiveDetails.highestNumber) {
objectiveDetails.highestNumber = objectiveDetail.number;
}
// add objectiveDetail to array
objectiveDetails.push(objectiveDetail);
}
例子:
var emptyObjectiveDetail = {
"number": 3,
"text": "",
"response": false,
"objectiveId": 412
};
objectiveDetails.add(emptyObjectiveDetail);
var emptyObjectiveDetail = {
"number": 2,
"text": "",
"response": false,
"objectiveId": 413
};
objectiveDetails.add(emptyObjectiveDetail);
var emptyObjectiveDetail = {
"text": "",
"response": false,
"objectiveId": 414
};
objectiveDetails.add(emptyObjectiveDetail);
var emptyObjectiveDetail = {
"number": objectiveDetails.highestNumber+1,
"text": "",
"response": false,
"objectiveId": 414
};
objectiveDetails.add(emptyObjectiveDetail);
console.log(objectiveDetails);