freeCodeCamp/guide/chinese/javascript/es6/default-parameters/index.md

45 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
title: Default Parameters
localeTitle: 默认参数
---
## 默认参数
如果您熟悉RubyPython等其他编程语言那么默认参数对您来说并不陌生。
默认参数是在声明函数时默认给出的参数。但是在调用函数时可以更改它的值。
```
let Func = (a, b = 10) => {
return a + b;
}
Func(20); // 20 + 10 = 30
```
在上面的例子中,我们只传递一个参数。该函数使用默认参数并执行该函数。
考虑另一个例子:
```
Func(20, 50); // 20 + 50 = 70
```
在上面的示例中,该函数采用两个参数,第二个参数替换默认参数。
考虑另一个例子:
```
let NotWorkingFunction = (a = 10, b) => {
return a + b;
}
NotWorkingFunction(20); // NAN. Not gonna work.
```
当您使用参数调用函数时,它们将按顺序分配。 (即)第一个值分配给第一个参数,第二个值分配给第二个参数,依此类推。
在上面的例子中值20被赋值给参数'a'而'b'没有任何值。所以我们没有得到任何输出。
但,
```
NotWorkingFunction(20, 30); // 50;
```
工作正常。