2016-03-03 27 views
0

我有一个对象称为响应与一系列问题。unshift和分配数组失败

我有这样的代码失败

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(…) 

对此,我感到很困惑,我有一个解决方案,但我不知道为什么它的工作原理。

+0

你能给更多的上下文吗?第一行和第二行之间肯定会发生一些事情,这些在问题中没有解释。 –

+1

第一个代码('self.qs.unshift(null);')与console.log代码('self.qs.questions.unshift(null)')不匹配。 – JJJ

+0

您能否纠正这个问题,以便一方面代码和另一方面控制台中的输出在不同的块中,并且对应?现在它很混乱。如上所述。也不清楚为什么在控制台中生成'undefined'。请提供一致的信息。 – trincot

回答

0

代码中存在拼写错误。

您的一系列问题是self.qs。您应该执行 self.qs,而不是self.qs.questions(这是undefined - 因此错误)。如您所知,使用angular.copy()返回原始数组的副本。在副本上执行unshift()会使原始数组完好无损,这通常是一种很好的做法。

修复错字应该可以解决您的问题。如你所怀疑的,angular.copy()在这种情况下不会有所作为。