Skip to content

函数

函数是一种特殊的值。

回调函数

js
function ask(question, yes, no) {
  if (confirm(question)) yes();
  else no();
}

function showOk() {
  alert("You agreed.");
}

function showCancel() {
  alert("You canceled the execution.");
}

// 用法:函数 showOk 和 showCancel 被作为参数传入到 ask
ask("Do you agree?", showOk, showCancel);

这个 showOkshowCancel 参数将函数作为值传入另一个函数进行调用的参数称之为回调函数

函数表达式 VS 函数声明

  • 函数表达式是在代码执行到达时被创建,并且仅从那一刻起可用
  • 在函数声明被定义之前,它就可以被调用
  • 严格模式下函数内部创建的函数声明只在当前代码块内可见,除非利用函数表达式将函数传递给外部:
js
let age = prompt("What is your age?", 18);
let welcome;
if (age < 18) {
  welcome = function() {
    alert("Hello!");
  };
} else {
  welcome = function() {
    alert("Greetings!");
  };
}
welcome(); // 现在可以了

箭头函数

只声明形参和返回值:

js
let func = (arg1, arg2, ..., argN) => expression;

如果带上花括号,则可以写成多行函数:

js
let sum = (a, b) => {  // 花括号表示开始一个多行函数
  let result = a + b;
  return result; // 如果我们使用了花括号,那么我们需要一个显式的 “return”
};

alert( sum(1, 2) ); // 3

标签语句

用于快速跳出 break / continue 继续某一层循环:

js
outerLoop: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) {
      continue outerLoop; // 跳过 outerLoop 的当前迭代
    }
    console.log(`i = ${i}, j = ${j}`);
  }
}