我正在研究这个Codepen。链接在这里。
http://codepen.io/sweenj7/pen/RPYrrE

我在这个特殊区域遇到麻烦。

 //This prints the entire array
        $scope.groups[i].items.push("Set " + j + " " +      exercises[i].weightReps );
      //This gets the following error TypeError: Cannot read property '0' of undefined
        //$scope.groups[i].items.push("Set " + j + " " + exercises[i].weightReps[i] );


我试图获取数组的每个值以在索引位置的手风琴列表中打印。出于某种原因,我收到了一个TypeError,未定义0,但是当我用weightReps而不是weightReps [i或1,2等]打印整个数组时,它会工作并打印整个数组。不知道该如何解决。

  angular.module('ionicApp', ['ionic'])

  .controller('MyCtrl', function($scope) {
 $scope.groups = [];

   var Bench = { name:"Bench", StartingSets:"5", Instructions:"lift up arm press to chest", weightSets: ["125","200","200","245","150"], weightReps: ["8","8","10","10","15"] };
   var Curls = { name:"Curls", StartingSets:"3", Instructions:"lift up arm"};
   var Squat = { name:"Squat", StartingSets:"4", Instructions:"Squat Down"};
var  exercises = new Array();
exercises[0] = Bench;
exercises[1] = Curls;
exercises[2] = Squat;

 for (var i=0; i < exercises.length; i++) {
for (var key in exercises[i]) {

$scope.groups[i] = {
  name: exercises[i][Object.keys(exercises[i])[0]] + ' - ' + exercises[i][Object.keys(exercises[i])[1]] + " Sets" ,
  items: []
}
};
$scope.groups[i].items.push(exercises[i].Instructions);
for (var j=1; j-1<exercises[i][Object.keys(exercises[i])[1]]; j++) {
  //for (var key in exercises[i]) {
 //   $scope.groups[i].items.push(JSON.stringify(exercises[i]) + '-' + j);
    //$scope.groups[i].items.push(exercises[i].StartingSets + '-' + j);
   //console.log(exercises[i].weightReps[i]);
  //This prints the entire array
    $scope.groups[i].items.push("Set " + j + " " + exercises[i].weightReps );
  //This gets the following error TypeError: Cannot read property '0' of undefined
    //$scope.groups[i].items.push("Set " + j + " " + exercises[i].weightReps[i] );

  //$scope.groups[i].items.push(exercises[i][key] + '-' + j);
}
  }

 /*
   * if given group is the selected group, deselect it
   * else, select the given group
   */
  $scope.toggleGroup = function(group) {
    if ($scope.isGroupShown(group)) {
  $scope.shownGroup = null;
} else {
  $scope.shownGroup = group;
}
  };
 $scope.isGroupShown = function(group) {
         return $scope.shownGroup === group;
  };

});

最佳答案

卷发和深蹲不具有属性weightReps,因此当您尝试阅读所述属性时,它会炸弹。

修改此集合以添加属性,但是您还需要向每个weightReps集合添加代表,以便在调用[object].weightReps[0]时不会返回null。

var Bench = { name:"Bench", StartingSets:"5", Instructions:"lift up arm press to chest", weightSets: ["125","200","200","245","150"], weightReps: ["8","8","10","10","15"] };
var Curls = { name:"Curls", StartingSets:"3", Instructions:"lift up arm", weightSets: [ADD SOME SETS HERE]};
var Squat = { name:"Squat", StartingSets:"4", Instructions:"Squat Down",weightSets: [ADD SOME SETS HERE]};

07-27 18:33