[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Functions/rest_parameters [Back]  [Original]

- JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Baseline

20169

JavaScript

function sum(...theArgs) {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

console.log(sum(1, 2, 3));
// : 6

console.log(sum(1, 2, 3, 4));
// : 10

js
function f(a, b, ...theArgs) {
  // 
}

  • 1

... 3 U+002E FULL STOP JavaScript

js
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// :
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]

js
function ignoreFirst(...[, b, c]) {
  return b + c;
}

js
function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}
function wrong3(...wrong,) {}
function wrong4(...wrong = []) {}

length

arguments

arguments 4

a 2 b

3 manyMoreArgs 3 4 5 6 n

js
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five", "six"] <-- 

1

js
// 

myFun("one", "two", "three");

// a, "one"
// b, "two"
// manyMoreArgs, ["three"] <--  1 

3 manyMoreArgs

js
// 

myFun("one", "two");

// a, "one"
// b, "two"
// manyMoreArgs, [] <-- 

1 b undefined manyMoreArgs

js
// 

myFun("one");

// a, "one"
// b, undefined
// manyMoreArgs, [] <-- still an array

theArgs length restParams.length arguments.length

js
function fun1(...theArgs) {
  console.log(theArgs.length);
}

fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3

2

js
function multiply(multiplier, ...theArgs) {
  return theArgs.map((element) => multiplier * element);
}

const arr = multiply(2, 15, 25, 42);
console.log(arr); // [30, 50, 84]

arguments

Array arguments

js
function sortRestArgs(...theArgs) {
  const sortedArgs = theArgs.sort();
  return sortedArgs;
}

console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7

function sortArguments() {
  const sortedArgs = arguments.sort();
  return sortedArgs; // 
}

console.log(sortArguments(5, 3, 7, 1));
// TypeError arguments.sort 

arguments

js
function fn(a, b) {
  const normalArray = Array.prototype.slice.call(arguments);
  //  or 
  const normalArray2 = [].slice.call(arguments);
  //  or 
  const normalArrayFrom = Array.from(arguments);

  const first = normalArray.shift(); // OK, gives the first argument
  const firstBad = arguments.shift(); // ERROR (arguments is not a normal array)
}

js
function fn(...args) {
  const normalArray = args;
  const first = normalArray.shift(); // OK, gives the first argument
}

ECMAScript 2027 LanguageSpecification
# sec-function-definitions


Web Proxy Viewer  |  New URL  |  Original Page