Skip to content

函数

学习如何函数 bundle reusable code, take 输入, and 返回输出 — 构建块 的 programs.

你将学到

  • 什么函数是 and 为什么我们 use 它们
  • 如何参数 and 实参工作
  • 如何 返回值 从函数
  • difference 之间定义 and calling 函数

概念讲解

函数

function 是一种 reusable block of code with a name. You define it once and call it many times. Functions are how you avoid repeating yourself (the DRY principle: Don't Repeat Yourself) and how you organize a program into understandable pieces.

Defining and Calling

// Define
function greet(name) {
  return "Hello, " + name + "!";
}

// Call
greet("Ada");   // "Hello, Ada!"
greet("Grace"); // "Hello, Grace!"

Parameters and Arguments

A parameter is the variable listed in the function definition (name above). An argument is the actual value you pass when calling ("Ada"). The parameter is a placeholder; the argument fills it in for that call.

Return Values

A function can return a value back to the caller with the 返回 keyword. Once 返回 runs, the function stops. If a function has no 返回, it returns undefined by default.

function add(a, b) {
  return a + b;
}
const sum = add(3, 4);  // 7

Why Functions Matter

Functions let you:

  1. Reuse code — write once, call many times.
  2. Abstract complexity — hide details behind a simple name.
  3. Test in isolation — a small function is easy to verify.
  4. Compose — call functions from other functions to build up behavior.

Modern JavaScript also has arrow functions, a shorter syntax: const add = (a, b) => a + b;. They behave like regular functions for most purposes.

示例代码

              // A function that calculates a discounted price
function applyDiscount(price, discountPercent) {
  const discount = price * (discountPercent / 100);
  return price - discount;
}

const original = 100;
const salePrice = applyDiscount(original, 20);
console.log(`$ ${original} with 20% off = $ ${salePrice}`);
// $ 100 with 20% off = $ 80

// Arrow function syntax (shorter):
const tax = (amount, rate) => amount * rate;
console.log(tax(80, 0.08));   // 6.4
            

applyDiscount takes two 参数 and 返回 result. arrow 函数 tax shows concise 语法 for 简单函数.

动手试一试

  • Hash Generator

    hash 函数 takes 输入 (文本) and 返回输出 (fixed-长度 hash). 相同输入总是 gives 相同输出.

常见错误

错误写法

Forgetting 到 call 函数 (referencing name 不使用 parentheses).

正确做法

greet 是函数对象; greet('Ada') calls 它. 如果你 see 函数源 printed 相反的 result, 你 forgot ().

错误写法

Expecting code 之后返回到 运行.

正确做法

返回 exits 函数 immediately. 任何行 之后它 是 unreachable. Put 你的最终 computation 之前返回语句.

相关代码片段

练习 函数

12 个练习

练习 函数

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误