9 JavaScript function函数
函数:就是把将一些语句进行封装,然后通过调用的形式,执行这些语句。
函数的作用:
- 解决大量的重复性的语句
- 简化编程,让编程模块化
# python 中声明函数
def add(x,y):
return x+y
# 调用函数
print(add(1,2))
//js中声明函数
function add(x,y){
return x+y;
}
//js中调用函数
console.log(add(1,2));
解释如下:
- function:是一个关键字。中文是“函数”、“功能”。
- 函数名字:命名规定和变量的命名规定一样。只能是字母、数字、下划线、美元符号,不能以数字开头。
- 参数:后面有一对小括号,里面是放参数用的。
- 大括号里面,是这个函数的语句。
1 函数表达式(匿名函数)
方式一:
var add = function (x,y) {
return x + y;
}
console.log(add(3,2))
方式二:
(function (){
console.log('匿名函数...')
})();
(function (x,y){
console.log('匿名函数...'+x+y)
})(1,2);
应用:
//匿名函数作为一个高阶函数使用
function bar(){
return function (){
console.log('高阶函数...')
}
}
bar()()
2 函数的作用域
//局部变量,是在函数内部声明,它的生命周期在当前函数被调用的时候,当函数调用完毕以后,则内存中自动销毁当前变量
//全局变量,是在函数外部声明,它的生命周期在当前文件中被声明以后就保存在内存中,直到当前文件执行完毕以后,才会被内存销毁掉
var a=1; //在函数体外的称为全局作用域
console.log(a);
function add() {
var a=3; //在函数体内的称为局部作用域(如果将var删掉,那么全局变量就会被局部重新赋值)
console.log(a); //3
}
add(a);
console.log(a); //1
3 函数全局污染问题
//index.js文件:
var name='lxx';
var hello=function () {
alert('hello '+name);
}
//first.js文件:
var name='wxx';
var hello=function () {
alert('hello '+name);
}
<body>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/first.js"></script>
<script>
hello();
hello();
</script>
</body>
此时调用hello函数,浏览器不知道是那个文件hello,则会按照执行顺序来,执行first.js文件的hello函数。
解决方案:
利用包裹的匿名函数来解决问题
//index.js文件
(function () {
var name='lxx';
var hello=function () {
alert('hello '+name);
}
window.index=hello;
})()
//first.js文件
(function () {
var name='wxx';
var hello=function() {
alert('hello '+name);
}
window.first=hello;
})()
<body>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/first.js"></script>
<script>
index();
first();
</script>
</body>
4 arguments伪数组
arguments代表的是实参。有个讲究的地方是:arguments只在函数中使用。
fn(2,4);
fn(2,4,6);
fn(2,4,6,8);
function fn(a,b,c) {
console.log(arguments);
console.log(fn.length); //获取形参的个数
console.log(arguments.length); //获取实参的长度
console.log("----------------");
}
结果:
2)之所以说arguments是伪数组,是因为:arguments可以修改元素,但不能改变数组的长短。举例:
fn(2,4);
fn(2,4,6);
fn(2,4,6,8);
function fn(a,b) {
arguments[0] = 99; //将实参的第一个数改为99
arguments.push(8); //此方法不通过,因为无法增加元素
}
5 空数组的方式
var array = [1,2,3,4,5,6];
array.splice(0); //方式1:删除数组中所有项目
array.length = 0; //方式2:length属性可以赋值,在其它语言中length是只读
array = []; //方式3:推荐
6 函数返回值
//如果没有设置返回值,那么返回undefined
function bar(){
console.log('lxx...');
}
var foo = bar(); //lxx...
console.log(foo); //undefined
//如果只声明变量不赋值,那么返回值是undefined
var name;
console.log(name); //
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix