当源是数组时,copy()返回对象

时间:2020-12-25 21:18:04

I want to create a copy of my arguments inside a logging function using angular.copy().

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

Since the arguments is already an Array, I expected to get an Array but it returned Object instead of Array.

由于参数已经是一个数组,所以我希望得到一个数组,但它返回的是对象而不是数组。

$scope.log = function(argN) {
    console.log("arguments", arguments, angular.copy(arguments));
    if (typeof(console) !== 'undefined') {
        console.log.apply(console, angular.copy(arguments));
    }
}
  1. Is this some sort of standard practice of copying?
  2. 这是某种复制的标准做法吗?
  3. How can I get Array instead of Object?
  4. 如何得到数组而不是对象?

2 个解决方案

#1


2  

arguments is not an array but array like. To do a shallow clone of arguments, use Array.prototype.slice.call(arguments). That will create an array of all the arguments. From there, to get a deep clone, use angular.copy.

参数不是数组,而是类似数组的数组。要对参数进行浅层克隆,请使用Array.prototype.slice.call(参数)。这将创建所有参数的数组。从那里,要得到一个深入的克隆,请使用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>

#2


0  

Edit: I think console.dir() maybe what you are looking for after reading this

编辑:我想是console.dir()也许是你读了之后想要的

Print JSON parsed object?

打印解析JSON对象?

#1


2  

arguments is not an array but array like. To do a shallow clone of arguments, use Array.prototype.slice.call(arguments). That will create an array of all the arguments. From there, to get a deep clone, use angular.copy.

参数不是数组,而是类似数组的数组。要对参数进行浅层克隆,请使用Array.prototype.slice.call(参数)。这将创建所有参数的数组。从那里,要得到一个深入的克隆,请使用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>

#2


0  

Edit: I think console.dir() maybe what you are looking for after reading this

编辑:我想是console.dir()也许是你读了之后想要的

Print JSON parsed object?

打印解析JSON对象?