【问题标题】:Push objects (same keys names) in array using angular.forEach ()使用 angular.forEach () 在数组中推送对象(相同的键名)
【发布时间】: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


    【解决方案1】:

    为什么要创建$scope 对象?正如您所发现的,这只会继续向您的数组添加相同的对象引用。怎么样:

    angular.forEach(['12', '43', 'Please, enter no.'], function (value, index) {
        if (isNaN (value)) {
            $scope.arr.push({ msg: 'Please, enter no.' });
        }
        else {
            $scope.arr.push({ msg: '' });
        }
    });
    

    【讨论】:

    • Lex :谢谢 yaar(在印度语中是朋友的意思).. 好把戏。它有效。
    【解决方案2】:

    现在,我得到上述代码错误输出的原因是我在 angular.forEach () 函数之外错误地声明了$scope.obj = {},但它应该在其中声明。通过这样做,每次迭代都会创建新对象。

    更正的 JS 代码:

    $scope.arr = []
    angular.forEach(['12', 'Please, enter no.', '43'], function (value, index) {
               $scope.obj = {}
               if (isNaN (value)) {
                    $scope.obj['msg'] = 'Please, enter no.';
                    $scope.arr.push($scope.obj);
               }
               else {
                    $scope.obj['msg'] = '';
                    $scope.arr.push($scope.obj);
               }
           });
    

    【讨论】:

    • 那你为什么要把它创建为一个范围对象呢?您可能最好省略该部分,因为它不提供额外功能,但在每次迭代期间将对象注册到范围。
    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 2017-08-09
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多