【发布时间】:2016-08-09 02:53:34
【问题描述】:
如何使用 angular.forEach() 函数将具有相同键名的对象推送到数组中?
例如,我声明了一个空数组,即$scope.arr = [] 和一个空对象,即$scope.obj = {}
现在使用angular.forEach() 和push() 函数,我怎样才能得到以下结果:
$scope.arr = [{msg: ''}, {msg: 'please, enter no.'}, {msg: ''}]
我的 JS 代码
$scope.arr = []
$scope.obj = {}
angular.forEach(['12', 'Please, enter no.', '43'], function (value, index) {
if (isNaN (value)) {
$scope.obj['msg'] = 'Please, enter no.';
$scope.arr.push($scope.obj);
}
else {
$scope.obj['msg'] = '';
$scope.arr.push($scope.obj);
}
});
当前错误输出: $scope.arr = [{msg: 'please, enter no.'}, {msg: 'please, enter no.'}, {msg: 'please, enter no.'}]
预期输出: $scope.arr = [{msg: ''}, {msg: 'please, enter no.'}, {msg: ''}]
我知道为什么我得到了错误的输出,因为所有 msg 键都使用数组的最后一个值进行了更新,但我找不到解决方法。
请帮帮我.....
【问题讨论】:
标签: angularjs