Sunday, 11 August 2013

Why does push not work when there's no collection defined in Javascript?

Why does push not work when there's no collection defined in Javascript?

I have the following code:
var maxNum = formData.answers = null ? Math.max.apply(Math,
formData.answers.map(function (o) { return o.number; })) : 0;
var emptyAnswer = {
"number": maxNum + 1,
"correct": false,
"name": "",
"notes": "",
"topicId": formData.topicId
};
formData.answers.push(emptyAnswer);
The code works if I already have an answers collection as part of formData
but if formData.answers is null then it does not work. It gives a message:
TypeError: Object 0 has no method 'push'
at Object.$scope.modalAddAnswer
(http://127.0.0.1:81/Content/app/admin/controllers/question-controller.js:113:30)
Is there a way I can refactor this to make it work if there are currently
no answers defined.

No comments:

Post a Comment