简体   繁体   中英

unshift and assigning an array is failing

I have a object called response with an array of questions.

I have this code that fails

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

and this code works:

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

Can someone explain what's going on.

Here's my console log:

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

I'm very confused about this, I have a solution but I am not sure why it works.

There's a typo in your code.

Your array of questions is self.qs . You should perform the unshift() on self.qs , and not on self.qs.questions (which is undefined - thus the error).

Using angular.copy() as you may know, returns a copy of the original array. Performing unshift() on the copy leaves the original array intact, which is generally a good practice.

Fixing the typo should solve your problem. angular.copy() , as you suspected, would not make a difference in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM