| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/rest_parameters | [Back] [Original] |
Get to know MDN better
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
function f(a, b, ...theArgs) {
//
}
... U+002E FULL STOP Array
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"]
function ignoreFirst(...[, b, c]) {
return b + c;
}
function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}
function wrong3(...wrong,) {}
function wrong4(...wrong = []) {}
arguments arguments Array sort()map()forEach() pop()arguments callee arguments ...restParam arguments ...restParam a b
manyMoreArgs n
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"] <--
//
myFun("one", "two", "three");
// a, "one"
// b, "two"
// manyMoreArgs, ["three"] <--
manyMoreArgs
//
myFun("one", "two");
// a, "one"
// b, "two"
// manyMoreArgs, [] <--
b undeifned manyMoreArgs
//
myFun("one");
// a, "one"
// b, undefined
// manyMoreArgs, [] <--
theArgs length restParams.length arguments.length
function fun1(...theArgs) {
console.log(theArgs.length);
}
fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3
function multiply(multiplier, ...theArgs) {
return theArgs.map((element) => multiplier * element);
}
const arr = multiply(2, 15, 25, 42);
console.log(arr); // [30, 50, 84]
Array arguments
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
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
}
function fn(...args) {
const normalArray = args;
const first = normalArray.shift(); //
}
| ECMAScript 2027 LanguageSpecification # sec-function-definitions |
| Web Proxy Viewer | New URL | Original Page |