Functions · 函数
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Functions
- A function is a named block of code you can run again and again.
function name(params) { ... return value; }. Theparamsare the inputs.returnhands a value back to whoever called the function.
中文
函数
- 函数(function)是一个有名字的代码块,可以反复运行。
function name(params) { ... return value; }。params是输入。return把一个值交回给调用函数的地方。
function square(n) {
return n * n;
}
console.log(square(6)); // → 36
English
Functions that just do something
- A function can do something (like print) instead of returning a value.
- Call it by writing its name and brackets:
greet("Ada").
中文
只做事、不返回的函数
- 函数可以做某件事(比如打印),而不返回值。
- 写下它的名字和括号来调用它:
greet("Ada")。
function greet(name) {
console.log("Hi, " + name); // → Hi, Ada
}
greet("Ada");
Explore · 探索
Call and return · 调用与返回
Each call runs the body with its own input, then return hands a value back. · 每次调用都用自己的输入运行函数体,然后 return 交回一个值。
English
Watch out
- The names in the brackets (
n,name) are parameters — they only exist inside the function. - A function with no
returngives backundefined. Addreturnwhen you want an answer out.
中文
注意
- 括号里的名字(
n、name)是参数(parameter)—— 它们只在函数内部存在。 - 没有
return的函数会交回undefined。想拿到答案时就加上return。
English
Common mistakes
returngives back a value; without it a function returnsundefined.- Call the function with
().
中文
常见错误
return返回一个值;没有它,函数返回undefined。- 用
()调用函数。
English
Now you try
- Write each function — it is called for you in the check.
- Press Check answer to test it.
中文
现在轮到你
- 写出每个函数 —— 检查时会替你调用它。
- 按检查答案来测试它。
Write a function double(n) that returns · 返回值 n times 2. · 写一个函数 double(n),返回 n 乘以 2。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a function add(a, b) that returns a + b. · 写一个函数 add(a, b),返回 a + b。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a function greet(name) that logs Hi, then the name, then call greet("Ada"). Output should be Hi, Ada. · 写一个函数 greet(name),打印 Hi, 再接名字,然后调用 greet("Ada")。输出应为 Hi, Ada。
Click Run to see the output here. · 点击“运行”查看此处输出。