处理数组时出现未定义的错误

时间:2016-10-03 15:23:58

标签: javascript angularjs

我有2个数组如下:

$scope.Stat.Statistics =[{val:10} , { val:11} , { val:13} ,{ val:14}]
$scope.selected = [{ val:12} , { val:13} ] //based on checkbox  selection

现在我只想将选定的值添加到Statistics数组中,并删除那些在选定但不存在的第一条统计记录中不存在的值。

预期输出

$scope.Stat.Statistics ={[ val:10]} , {[ val:12]} , {[ val:13]}

代码:

for (var i = 0; i < selected.length; i++) {
    for (var j = 1; j <= $scope.Stat.Statistics.length; j++) {
        //ignore 1st record for comparision
        if (selected[i].val != $scope.Stat.Statistics[j].val) {
            $scope.Stat.Statistics.splice(j, 1);
            $scope.Stat.Statistics[j].push(selected[i]);
        }
    }
}

更新:如果Statisticsselected中的值相同,我希望保留统计值。

  

错误:$ scope.Stat.Statistics [j]未定义

2 个答案:

答案 0 :(得分:2)

$scope.Stat.Statistics ={[ val:10]} , {[ val:11]} , {[ val:13]} ,{[ val:14]}

这不是有效的Javascript。如果你想要一个数组,你应该定义它:

$scope.Stat.Statistics =[{val:10} , { val:11} , { val:13} ,{ val:14}]

&#13;
&#13;
var Statistics = [{
  val: 10
}, {
  val: 11
}, {
  val: 13
}, {
  val: 14
}];

var selected = [{
  val: 12
}, {
  val: 13
}];

var found = selected;
Statistics.map(function(statistic) {
  selected.map(function(selectedItem) {
    if(selectedItem.val === statistic.val) {
      found.push(selectedItem); 
    }
  });
});

console.log(found);
&#13;
&#13;
&#13;

当然,我已经将Angular元素排除在外,但同样的逻辑也应该有效。

答案 1 :(得分:1)

您可以使用$scope.Stat.Statistics的第一个元素,您希望将$scope.selected保留并连接到第一个元素。

var $scope = { Stat: {} };

$scope.Stat.Statistics = [{ val: 10 }, { val: 11 }, { val: 13 }, { val: 14 }];
$scope.selected = [{ val: 12 }, { val: 13 }];
$scope.Stat.Statistics = [$scope.Stat.Statistics[0]].concat($scope.selected);

console.log($scope.Stat.Statistics);

编辑:保持公共项目具有相同的val并将其余项目附加到数组中。

var $scope = { Stat: {} },
    hash = {},
    i;

$scope.Stat.Statistics = [{ val: 10 }, { val: 11 }, { val: 13, extra: 42 }, { val: 14 }];
$scope.selected = [{ val: 12 }, { val: 13 }];

$scope.selected.forEach(function (a) {
    hash[a.val] = a;
});

i = $scope.Stat.Statistics.length;
while (i--) {
    if (hash[$scope.Stat.Statistics[i].val]) {
        delete hash[$scope.Stat.Statistics[i].val];
        continue;
    }
    if (i === 0) {
        continue;
    }
    $scope.Stat.Statistics.splice(i, 1);
}
Object.keys(hash).forEach(function (k) {
    $scope.Stat.Statistics.push(hash[k]);
});

console.log($scope.Stat.Statistics);