javascript - 当源为数组时,angular.copy() 返回对象

标签 javascript angularjs arrays

我想使用 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));
    }
}
  1. 这是某种标准的复制做法吗?
  2. 如何获取数组而不是对象?

最佳答案

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/

相关文章:

javascript - 如何在JavaScript中使用字节数组将字符串转换为base64编码?

javascript - 卡在新铁路围栏密码中的解密(之字形模式)

c# - c# arraylist 中的对象

javascript - 从 JSON 对象创建 HTML

javascript - 在 JavaScript 中获取数组的深度

Javascript删除合并某些属性的对象列表中的重复项

javascript - 在javascript中每15毫秒进行一次API调用

javascript - 无法将模型绑定(bind)到模板

javascript - 与过滤器的一次性绑定(bind)不起作用

c# - SignalR 错误 "No connection could be made because the target machine actively refused it"