[英]Do I need to specify object type when creating globals in Javascript?
[英]Do I need to define an array object when populating it with a ForEach in Javascript?
我有以下代碼:
if (!$scope.aa.hasOwnProperty('x')) {
$scope.aa.x = {}
data.answers.forEach(function (element, index) {
$scope.aa.x[index].c = null;
$scope.aa.x[index].r = null;
$scope.aa.x[index].text = element.text;
});
}
但這給了我一個錯誤:
TypeError: Cannot set property 'c' of undefined
我是否需要為aa
定義一個數組,如果要怎么做?
CD的答案的另一個更慣用的版本是:
$scope.aa.x[index] = {
c : null,
r : null,
text : element.text
}
是。 看起來x
是一個array
, x[index]
是一個object
:
$scope.aa.x = [];
data.answers.forEach(function (element, index) {
$scope.aa.x[index] = {};
$scope.aa.x[index].c = null;
$scope.aa.x[index].r = null;
$scope.aa.x[index].text = element.text;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.