在 Javascript 中使用 ForEach 填充数组对象时,我是否需要定义一个数组对象

Do I need to define an array object when populating it with a ForEach in Javascript?

本文关键字:数组 对象 定义 一个 是否 Javascript ForEach 填充      更新时间:2023-09-26

我有以下代码:

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是一个arrayx[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;  
        });