在Javascript中用ForEach填充数组对象时,是否需要定义数组对象?
我有以下代码:在Javascript中用ForEach填充数组对象时,是否需要定义数组对象?,javascript,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; });
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
定义一个数组?如果需要,我该怎么做?是。看起来x
是一个数组
,x[index]
是一个对象
:
$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;
});
对。看起来
x
是一个数组
,x[index]
是一个对象
:
$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;
});
对。看起来
x
是一个数组
,x[index]
是一个对象
:
$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;
});
对。看起来
x
是一个数组
,x[index]
是一个对象
:
$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;
});
CD回答的另一个更惯用的版本是:
$scope.aa.x[index] = {
c : null,
r : null,
text : element.text
}
CD回答的另一个更惯用的版本是:
$scope.aa.x[index] = {
c : null,
r : null,
text : element.text
}
CD回答的另一个更惯用的版本是:
$scope.aa.x[index] = {
c : null,
r : null,
text : element.text
}
CD回答的另一个更惯用的版本是:
$scope.aa.x[index] = {
c : null,
r : null,
text : element.text
}