Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中用ForEach填充数组对象时,是否需要定义数组对象?_Javascript - Fatal编程技术网

在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
}