C语言函数
C语言有参数声明函数和无参数声明函数,递归函数的区别。
有参数声明函数
int add(int a, int b) {
return a + b;
}//有参数函数
有参数函数就像射箭一定朝着靶(参数)的方向射,在调用函数的时候必须给到参数
无参数声明函数
#include <stdio.h>
void mix_ingredients() {
// 在这里处理食材
printf("混合食材\n");
}
void bake_in_oven() {
// 在这里将混合好的食材放入烤箱
printf("将混合好的食材放入烤箱\n");
}
int main() {
mix_ingredients();
bake_in_oven();
return 0;
}
无声明的函数就像两个不认识的人打招呼,双方不需要知道对方的名字
递归函数
#include <stdio.h>
// 递归函数来计算n的阶乘
int factorial(int n) {
// 基本情况:当n等于0或1时,直接返回1
if (n == 0 || n == 1) {
return 1;
}
// 递归情况:调用函数自身来计算n的阶乘
else {
return n * factorial(n - 1);
}
}
int main() {
int n = 5;
int result = factorial(n);
printf("Factorial of %d is %d\n", n, result);
return 0;
}
递归函数简单地说就是main函数里调用自己定义的函数,通俗易懂地例子就像你吃汉堡,每次只吃一半,下一次还是一半的一半,直到吃完为止。
Javascript函数
标准函数
let randomNumber = Math.random() * 100;
console.log(randomNumber);
Math.random()是产生随机数的函数。还有`Array.prototype.push()`等
用户自定义函数
function sayHello(name, age) {
console.log("Hello, my name is " + name + " and I'm " + age + " years old.");
}
sayHello("Alice", 30);
其实C语言中也有用户自定义函数如上面的无参数函数声明的mix_ingredients函数
事件处理函数
用于处理鼠标点击,移动事件
回调函数
function downloadFile(fileUrl, callback) {
// 下载文件的相关操作
let downloaded = 0;
const total = 100;
function updateProgress(percentage) {
console.log("Download progress: " + percentage + "%");
}
function finishDownload() {
console.log("Download finished!");
}
// 模拟下载进度
for (let i = 0; i < total; i++) {
setTimeout(() => {
downloaded += 1;
updateProgress(downloaded);
if (downloaded === total) {
finishDownload();
}
}, 100);
}
}
downloadFile("https://example.com/file.zip", updateProgress);
在for循环里面调用updateProgress,finishDownload函数,它与递归函数不同,递归函数是把一个解决方法封装进函数体,而回调函数更像是调用的时候执行操作
闭包函数
let sum = 0;
function calculateSum(arr) {
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
闭包函数可以访问到外部的变量,就像sum变量在函数体外部,但在函数体内部仍然可以使用
匿名函数
let fn = function() {
console.log("Hello, world!");
};
fn(); // 输出 "Hello, world!"
没有函数名的函数
箭头函数
const arrowFn = () => {
console.log("Hello, world!");
};
arrowFn(); // 输出 "Hello, world!"
使用箭头=>
语法定义的函数,可以省略function的名字,有时只有一个参数的时候可以省略()