freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../es6/set-default-parameters-for-...

1.3 KiB

id title challengeType forumTopicId dashedName
587d7b88367417b2b2512b46 设置函数的默认参数 1 301209 set-default-parameters-for-your-functions

--description--

ES6 里允许给函数传入默认参数,来构建更加灵活的函数。

请看以下代码:

const greeting = (name = "Anonymous") => "Hello " + name;

console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous

默认参数会在参数没有被指定(值为 undefined )的时候起作用。在上面的例子中,参数name会在没有得到新的值的时候,默认使用值 "Anonymous"。你还可以给多个参数赋予默认值。

--instructions--

给函数increment加上默认参数,使得在value没有被赋值的时候,默认给number加1。

--hints--

increment(5, 2)的结果应该为7

assert(increment(5, 2) === 7);

increment(5)的结果应该为6

assert(increment(5) === 6);

参数value的默认值应该为1

assert(code.match(/value\s*=\s*1/g));

--seed--

--seed-contents--

// Only change code below this line
const increment = (number, value) => number + value;
// Only change code above this line

--solutions--

const increment = (number, value = 1) => number + value;