R / Richie全部文章 ↑

前端 · 2 分钟阅读

函数

目录


概述

函数是一段带圆括号 () 的可重用代码块,用来执行特定任务。它可以接收参数、返回结果,并拥有独立的作用域。

浏览器内置函数

字符串操作

// 替换字符串
const myText = "Hello world"
const newString = myText.replace("world", "earth")
console.log(newString)  // 输出: Hello earth

数组操作

// 数组转字符串
const myArray = ["a", "b", "c"]
const madeAString = myArray.join(",")
console.log(madeAString)  // 输出: a,b,c

数学运算

// 生成随机数
const myNumber = Math.random()
console.log(myNumber)  // 输出: 0-1 之间的随机数

函数与方法

类型 说明 示例
函数 独立的功能块 function greet() {}
方法 对象的成员函数 object.method()

更多内置函数和方法:JavaScript 标准内置对象

调用函数

基本语法

function myFunction() {
    alert("你好")
}

myFunction()  // 调用函数

函数参数

参数类型

类型 说明 示例
必需参数 必须传入的参数 function(a, b) {}
可选参数 可以省略的参数 function(a, b = 1) {}
剩余参数 接收多个参数 function(...args) {}

参数示例

// 默认参数
function greet(name = "Guest") {
    return `Hello, ${name}!`;
}

// 多个参数
function add(a, b = 0) {
    return a + b;
}

匿名函数和箭头函数

匿名函数

命名函数

function myFunction() {
    alert("hello")
}

匿名函数

// 基本形式
(function () {
    alert("hello")
})

// 作为参数
element.addEventListener("click", function() {
    alert("Clicked!");
});

事件处理示例

// 命名函数方式
function logKey(event) {
    console.log(`You pressed this "${event.key}"`)
}
textBox.addEventListener("keydown", logKey)

// 匿名函数方式
textBox.addEventListener("keydown", function (event) {
    console.log(`You pressed this "${event.key}"`)
})

箭头函数

基本语法

// 完整语法
textBox.addEventListener("keydown", (event) => {
    console.log(`You pressed this "${event.key}"`)
})

// 单参数简写
textBox.addEventListener("keydown", event => {
    console.log(`You pressed this "${event.key}"`)
})

// 单行返回值简写
const originals = [1, 2, 3]
const doubled = originals.map(item => item * 2)
console.log(doubled)  // 输出: [2,4,6]

等价写法

// 箭头函数完整写法
const double = (item) => {
    return item * 2;
};

// 传统函数写法
function doubleItem(item) {
    return item * 2
}

实际应用示例

<input id='textBox' type="text" />
<div id="output"></div>
// 实时显示用户输入
const textBox = document.querySelector("#textBox")
const output = document.querySelector("#output")

textBox.addEventListener("keydown", (event) => {
    output.textContent = `You pressed this "${event.key}"`
})