JavaScript中的arguments对象是一个奇怪的东西——它在大多数情况下就像一个数组,但实际上它不是一个数组对象。因为它是完全不同的东西,它没有数组中的有用函数。比如forEach, sort, filter和map。

用简单的for循环从arguments对象构造一个新数组非常简单。例如,这个函数对它的参数进行排序:

function sortArgs() {
    var args = [];
    for (var i = 0; i < arguments.length; i++)
        args[i] = arguments[i];
    return args.sort();
}

然而,仅仅为了访问非常有用的JavaScript数组函数,就必须这么做,这是一件相当可怜的事情。是否有一种内置的方法来使用标准库?


当前回答

 function x(){
   var rest = [...arguments]; console.log(rest);return     
   rest.constructor;
 };
 x(1,2,3)

我尝试了简单的破坏技巧

其他回答

这里有一个简洁明了的解决方案:

函数argsToArray() { 返回Object.values(参数); } //使用实例 console.log ( argsToArray(1, 2, 3, 4, 5) .map(arg => arg*11) );

对象。values()将以数组的形式返回对象的值,由于arguments是一个对象,它本质上将参数转换为数组,从而为您提供数组的所有辅助函数,如map、forEach、filter等。

尝试使用Object.setPrototypeOf()

解释:将参数的原型设置为Array.prototype

函数toArray() { 返回对象。Array.prototype setPrototypeOf(参数) } console.log (toArray(“abc”,123年,{def: 456}, [0, [7, [14]]]))


说明:取参数的每个索引,将item放入数组中对应的数组索引处。

也可以使用Array.prototype.map()

function toray () return键[]文件夹。电话(论据,(_,k,a) => a[k]) 的 控制台日志(toArray(“abc”,123,{def: 456} [0, [7], [14]])


说明:取参数的每个索引,将item放入数组中对应的数组索引处。

循环的. .

函数toArray() { Let arr = [];For (let prop of arguments) arr.push(prop);返回加勒比海盗 } console.log (toArray(“abc”,123年,{def: 456}, [0, [7, [14]]]))


或Object.create ()

说明:创建对象,将对象的属性设置为每个参数索引处的项;设置创建对象的原型为Array.prototype

函数toArray() { Var obj = {}; For (var prop in arguments) { Obj[道具]= { 价值:参数(道具) 可写:没错, 可列举的:真的, 可配置:真 } } 返回Object.create(数组。原型,obj); } console.log (toArray(“abc”,123年,{def: 456}, [0, [7, [14]]]))

这是一个非常老的问题,但我认为我有一个解决方案,它比以前的解决方案更容易输入,并且不依赖于外部库:

function sortArguments() {
  return Array.apply(null, arguments).sort();
}

本什马克3方法:

function test()
{
  console.log(arguments.length + ' Argument(s)');

  var i = 0;
  var loop = 1000000;
  var t = Date.now();
  while(i < loop)
  {
      Array.prototype.slice.call(arguments, 0); 
      i++;
  }
  console.log(Date.now() - t);


  i = 0,
  t = Date.now();
  while(i < loop)
  {
      Array.apply(null, arguments);
      i++;
  }
  console.log(Date.now() - t);

  i = 0,
  t = Date.now();
  while(i < loop)
  {
      arguments.length == 1 ? [arguments[0]] : Array.apply(null, arguments);
      i++;
  }
  console.log(Date.now() - t);
}

test();
test(42);
test(42, 44);
test(42, 44, 88, 64, 10, 64, 700, 15615156, 4654, 9);
test(42, 'truc', 44, '47', 454, 88, 64, '@ehuehe', 10, 64, 700, 15615156, 4654, 9,97,4,94,56,8,456,156,1,456,867,5,152489,74,5,48479,89,897,894,894,8989,489,489,4,489,488989,498498);

结果呢?

0 Argument(s)
256
329
332
1 Argument(s)
307
418
4
2 Argument(s)
375
364
367
10 Argument(s)
962
601
604
40 Argument(s)
3095
1264
1260

享受吧!

如果你正在使用jQuery,在我看来,下面的代码更容易记住:

function sortArgs(){
  return $.makeArray(arguments).sort();
}