【问题标题】:angular.copy() returning Object when source is Array当源为数组时,angular.copy() 返回 Object
【发布时间】:2017-01-14 05:42:32
【问题描述】:

我想使用 angular.copy() 在日志记录函数中创建我的 arguments 的副本。

由于arguments 已经是一个数组,我希望得到一个数组,但它返回的是 Object 而不是 Array。

$scope.log = function(argN) {
    console.log("arguments", arguments, angular.copy(arguments));
    if (typeof(console) !== 'undefined') {
        console.log.apply(console, angular.copy(arguments));
    }
}
  1. 这是某种标准的复制做法吗?
  2. 如何获取 Array 而不是 Object?

【问题讨论】:

  • arguments 不是数组。

标签: javascript angularjs arrays


【解决方案1】:

编辑:我认为console.dir() 可能是您在阅读此内容后正在寻找的内容

Print JSON parsed object?

【讨论】:

    【解决方案2】:

    arguments 不是数组,而是类似数组。要对arguments 进行浅层克隆,请使用Array.prototype.slice.call(arguments)。这将创建一个包含所有参数的数组。从那里,要获得深度克隆,请使用angular.copy

    var foo = angular.module('foo', []);
    
    foo.controller('bar', function($scope) {
       $scope.trace = function() {
           var clonedArguments = angular.copy(arguments);
           console.log(clonedArguments);
           var clonedArgs = angular.copy(Array.prototype.slice.call(arguments));
           console.log(clonedArgs);
       };
      $scope.trace(1, 'foo', { bar: 27 })
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="foo" ng-controller="bar"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多