簡體   English   中英

在Java中使用ForEach填充數組對象時是否需要定義數組對象?

[英]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是一個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;  
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM