unshift和分配数组失败

时间:2016-03-03 19:14:17

标签: javascript angularjs

我有一个名为响应的对象,其中包含一系列问题。

我的代码失败了

    self.qs = response.questions;
    self.qs.unshift(null);

并且此代码有效:

    self.qs = angular.copy(response.questions);
    self.qs.unshift(null);

有人可以解释发生了什么。

这是我的控制台日志:

console.log(JSON.stringify(self.qs))
VM919:1 [{"answer":null,"answerGridCorrect":null,"answerGridResponses":null,"answered":false,"correctCount":0,"hint":null,"incorrectCount":0,"questionNumber":1,"questionUId":"511efb60-f909-4cd1-894f-e313f2c990b0","locked":false,"result":"N","shownCount":0,"tagged":false,"text":"How many legs do cats have?","userTestQuestionId":14546,"answerGrid":[{"answerId":4996,"text":"1","correct":null,"response":null},{"answerId":4997,"text":"4","correct":null,"response":null},{"answerId":4998,"text":"3","correct":null,"response":null},{"answerId":4999,"text":"2","correct":null,"response":null}]},{"answer":null,"answerGridCorrect":null,"answerGridResponses":null,"answered":false,"correctCount":0,"hint":null,"incorrectCount":0,"questionNumber":2,"questionUId":"458559e0-e4fe-4830-a276-ec3633b5bf64","locked":false,"result":"N","shownCount":0,"tagged":false,"text":"How many legs do dogs have?","userTestQuestionId":14547,"answerGrid":[{"answerId":4992,"text":"2","correct":null,"response":null},{"answerId":4993,"text":"4","correct":null,"response":null},{"answerId":4994,"text":"1","correct":null,"response":null},{"answerId":4995,"text":"3","correct":null,"response":null}]}]
undefined
self.qs.questions.unshift(null)
VM921:1 Uncaught TypeError: Cannot read property 'unshift' of undefined(…)

我对此非常困惑,我有一个解决方案,但我不确定它为什么会起作用。

1 个答案:

答案 0 :(得分:0)

您的代码中存在拼写错误。

您的一系列问题是self.qs。您应该在unshift()上执行self.qs,而不是self.qs.questionsundefined - 这样的错误)。

如您所知,使用angular.copy()返回原始数组的副本。在副本上执行unshift()会使原始数组保持原样,这通常是一种很好的做法。

修复拼写错误应解决您的问题。正如您所怀疑的那样,angular.copy()在这种情况下不会有所作为。