JavaScript中的函数
函数的声明
第一种方法,用function
命令声明
function print() {
console.log("Hello world!");
}
第二种方法,用函数表达式
声明
//这种方法是将匿名函数赋值给变量,`=`右边是匿名函数,又称函数表达式,大括号外面要加分号
let print = function() {
console.log("Hello world!");
};
另外es6
中函数表达式声明可以用箭头=>
函数简写为:
let print = () => {
console.log("Hello world!");
};
另外需要注意的是,利用
function
命令声明函数时,整个函数会被提升到代码头部,这叫函数声明提升
,但是其他方式声明的函数不会提升到代码头部。除此以外若函数重复声明,则后面声明的函数将覆盖前面的函数。
立即执行函数
当函数只使用一次,通常使用IIFE(Immediately Invoked Function Expression)
//本质是一个匿名函数,因此在立即调用之后将无法再次调用
(function() {
console.log("这个函数只执行一次");
})();
函数参数
与Java
不同,Js
函数传参时允许传入任意个参数而不影响调用
// 参数 figure(位数) txt(文本)
function code(figure, txt) {
const num1 = Math.random() * 0.9 + 0.1;
const num2 = Math.floor(num1 * Math.pow(10, figure));
console.log(txt + num2);
}
code(6, "六位随机数:"); //六位随机数:556540
code(6); //undefined 556540
code(6, "六位随机数:", "第三个参数"); //六位随机数:556540
并且我们可以给参数设置默认值,即如果没有参数的传入,则使用默认值
// 参数 figure(位数) txt(文本)
function code(figure, txt = "随机数:") {
const num1 = Math.random() * 0.9 + 0.1;
const num2 = Math.floor(num1 * Math.pow(10, figure));
console.log(txt, num2);
}
code(6); //随机数: 556540
计时器(内置函数)
延时执行 setTimeout()
//第一个参数为一个函数或一段代码,第二个参数为延迟的时间(单位:ms)
//该函数会返回一个整数,作为该计时器的ID,用于取消该定时器
let timerId = settimeout(func|'code',delay);
//注意代码需要用引号包裹
let timerId = setTimeout('console.log(2)', 1000);
//清除计时器
clearTimeout(timerId);
无限调用 setInterval()
用法与
setTimeout()
一致,区别是setInterval()
指定某个任务每隔一段时间就执行一次,也就是无限次的定时执行
let i = 60;
print();
let timer = setInterval(print, 1000);
//每隔1s打印一个数字
function print() {
console.log(i);
i--;
if (i < 1) {
clearInterval(timer);
}
}