JavaScript - arguments object

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方法。 可是它能夠轉換爲真正的數組:spa

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

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

Example:prototype

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]
相關文章
相關標籤/搜索