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

- JavaScript | MDN

MDN Web Docs

View in English Always switch to English

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) {
  // 
}

... U+002E FULL STOP Array

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

a b

manyMoreArgs 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"] <-- 

js
// 

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

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

manyMoreArgs

js
// 

myFun("one", "two");

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

b undeifned manyMoreArgs

js
// 

myFun("one");

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

argument

theArgs length restParams.length arguments.length

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

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

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));
//  TypeErrorarguments.sort is not a function

arguments

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

  const first = normalArray.shift(); // 
  const firstBad = arguments.shift(); // arguments 
}

js
function fn(...args) {
  const normalArray = args;
  const first = normalArray.shift(); // 
}

ECMAScript 2027 LanguageSpecification
# sec-function-definitions


Web Proxy Viewer  |  New URL  |  Original Page