当前位置: 首页 > Web前端 > JavaScript

JavaScript函数和方法详解

时间:2023-03-27 13:13:44 JavaScript

1.什么是函数?由函数关键字、函数名和一些语句组成的函数体称为函数。在JavaScript中,函数和其他对象一样有属性和方法,不同的是函数可以被调用。如果函数中没有使用return语句,则默认返回undefined。2.定义函数的方法1.函数声明函数声明定义了一个带有指定参数的函数。//1.语法functionname([param[,param[,...param]]]){statements}//2.可以在函数声明之前调用函数,不会有语法问题hoisted();//"foo"functionhoisted(){console.log("foo");}2.函数表达式//语法varmyFunction=functionname([param[,param[,...param]]]){statements}//匿名写法varmyFunction=function(){//语句}//命名写法varmyFunction=functionnamedFunction(){//语句}//例子varfoo=function(){}foo.name//"foo"varfoo2=foofoo2.name//"foo"varbar=functionbaz(){}bar.name//"baz"console.log(foo===foo2);//trueconsole.log(typeofbaz);//undefinedconsole.log(bar===baz);//false(errorsbecausebaz==undefined)//在函数表达式之前调用函数会导致语法错误。未提升();//类型错误:notHoisted不是函数varnotHoisted=function(){console.log("bar");};3.动态创建函数//方法一:使用函数表达式创建varmyFunc;if(num==0){myFunc=function(theObject){theObject.make="Toyota"}}//方法二:使用Function对象创建varx=10;functioncreateFunction1(){varx=20;返回新函数('返回x;');//这里x指向最顶层全局作用域中的x}4.箭头函数(=>)箭头函数以更简洁的方式表示函数。更多内容,请看这里!//语法1([param][,param])=>{statements}//语法2param=>expressionvara=["Hydrogen","Helium","Lithium","Beryllium"];//普通函数vara2=a.map(function(s){returns.length});控制台日志(a2);//logs[8,6,7,9]//箭头函数vara3=a.map(s=>s.length);控制台日志(a3);//logs[8,6,7,9]5.Generatorfunction使用function*定义一个函数,返回一个Generator对象,称为generatorfunction。使用yield关键字,它可以变成一个异步函数。详情请看这里!6、AsyncFunction可以使用AsyncFunction对象动态创建异步函数。AsyncFunction不是全局对象,需要通过Object.getPrototypeOf(asyncfunction(){}).constructor生成。JavaScript中的每个异步函数都是AsyncFunction的对象。更多内容,请看这里!//示例函数resolveAfter2Seconds(x){returnnewPromise(resolve=>{setTimeout(()=>{resolve(x);},2000);});}varAsyncFunction=Object.getPrototypeOf(asyncfunction(){}).constructor;vara=newAsyncFunction('a','b','returnawaitresolveAfter2Seconds(a)+awaitresolveAfter2Seconds(b);');a(10,20).then(v=>{控制台.log(v);//4秒后打印30};3.函数参数1,默认参数//1,参数默认值为undefinedfunctionmultiply(a,b){b=(typeofb!=='undefined')?b:1;returna*b;}multiply(5);//5//2.使用默认参数重用上述函数functionmultiply(a,b=1){returna*b;}multiply(5);//还有5个内容,看这里!2.剩余参数用...表示一个不确定量的剩余参数。更多内容,请看这里!//1.语法function(a,b,...theArgs){//...}//2.示例函数multiplier,...theArgs){returntheArgs.map(x=>multiplier*x);}vararr=multiply(2,1,2,3);控制台日志(arr);//[2,4,6]3.argumentsarguments是一个数组对象,包含函数的实际参数。更多内容,请看这里!functionmyConcat(separator){varresult='';变量我;for(i=1;i