我想使用 angular.copy()
在日志记录函数中创建我的参数
的副本。
由于arguments
已经是一个数组,我希望得到一个数组,但它返回了对象而不是数组。
$scope.log = function(argN) {
console.log("arguments", arguments, angular.copy(arguments));
if (typeof(console) !== 'undefined') {
console.log.apply(console, angular.copy(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>
关于javascript - 当源为数组时,angular.copy() 返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354538/