JavaScript

The arguments object is an Array-like object corresponding to the arguments passed to a function.

function func1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 1

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 3
}

func1(1, 2, 3);

arguments对象是所有(非箭头)函数中可用的局部变量。 您可以使用arguments对象在函数内引用函数的参数。 此对象包含传递给函数的每个参数的条目,第一个条目的索引从0开始。

arguments对象不是Array。 它类似于Array,但除了length之外没有任何Array属性。 例如,它没有pop方法。 但是它可以转换为真正的数组:

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);

// ES2015
const args = Array.from(arguments);

Example:

function myConcat(separator) {
  var args = Array.prototype.slice.call(arguments, 1);
  return args.join(separator);
}

// returns "red, orange, blue"
myConcat(', ', 'red', 'orange', 'blue');

// returns "elephant; giraffe; lion; cheetah"
myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');

// returns "sage. basil. oregano. pepper. parsley"
myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
function list(type) {
  var result = '<' + type + 'l><li>';
  var args = Array.prototype.slice.call(arguments, 1);
  result += args.join('</li><li>');
  result += '</li></' + type + 'l>'; // end list

  return result;
}

var listHTML = list('u', 'One', 'Two', 'Three');

/* listHTML is:

"<ul><li>One</li><li>Two</li><li>Three</li></ul>"

*/
function foo(...args) {
  return args;
}
foo(1, 2, 3); // [1,2,3]
原文地址:https://www.cnblogs.com/sufei-duoduo/p/9512800.html