批改状态:合格
老师批语:
// function hello(参数){// return 返回值// }function hello(username){return 'hello,'+username;}console.log(hello('大家好'));
1.参数不足:给个默认值
function hello(username='admin'){return 'hello,'+username;}console.log(hello());
2.参数过多:...(rest只是标识符)
function hello(...users){return users;}console.log(hello('同学们','大家好','开始上课'));
注:(…)用在函数参数中它的功能是压入到数组中;(…)用在函数调用时它的功能是展开数组;
3.返回值(默认是单值)
当业务需要返回多个值,需将多个值包装到一个容器中(容器:数组、对象)
3.1数组
// 数组const f=()=>[1,2,3];console.log(f());
3.2对象
如果只返回一个对象字面量,必须将返回的对象转为表达式(加个圆括号({}))再返回
f=()=>({a:1,b:2,get:function(){return'ok';},});console.log(f());
let name='朱老师';console.log(name);let user={// name:'朱老师',}console.log(user.name);
let name='马老师';let email='a@qq.com';let user={name,email,// getuserinfo:function(){// return this.name+':'+this.email;// },// 方法简写:将“:function”删掉即可getuserinfo(){return this.name+':'+this.email;},}console.log(user.name);console.log(user.email);console.log(user.getuserinfo());
注:箭头函数不要使用在对象字面量中;
1.模板字面量
console.log('hello 朱老师');// 'hello 朱老师':字符串// 'hello username':模板字符串,username>占位符/插值/表达式let username='朱老师';// 'hello'插值之外的字符串叫字面量console.log('hello'+username);// 模板字符串,用的是反引号(``)console.log(`hello ${username}`);// 10+40:插值表达式console.log(`10+40= ${10+40}`);// ${age>=18?`成年` :`未成年`}:三元表达式let age=10;console.log(`${age>=18?`成年` :`未成年`}`);
2.模板函数/标签函数(用“模板字面量”作为参数的函数)
// alert:函数名;`hello php.cn`:函数参数,不需要括号alert`hello php.cn`;// 注:模板函数声明和普通函数一样,只不过在调用时使用“模板字面量”作为参数// function total(参数1,参数2)// 参数1:必须是当前模板字面量参数中的字符串字面量组成的数组// 参数2:必须是一个或多个模板字面量中的插值列表function total(strings,...args){console.log(strings);console.log(args);}let name='手机';let num=10;let price=500;total`名称:${name},数量:${num},单价:${price}`;
// d:自由变量(函数外部的变量)let d=40;// a,b:参数变量let fn=function(a,b){// c:私有变量/内部变量/局部变量let c=30;return a+b+c+d;};console.log(fn(10,20));
函数内部可用的三种变量:
1.参数变量:函数参数列表中shengm
2.私有变量:函数内部声明
3.自由变量:函数外部声明
形成闭包的二个条件:
1.父子函数
2.子函数中调用父函数中的变量
// fn:父函数// f:子函数// a:父函数中的参数变量// b:子函数中的参数变量fn=function(a){let f=function(b){return a+b;};return f;};let f1=fn(10);console.log(f1(20));
1.偏函数(高阶函数)
fn=function(a,b,c){return a+b+c;};console.log(fn(1,2,3));
使用闭包,可以将函数调用时的多个参数打散以此传入(柯里化)
fn=function(a){return function(b){return function(c){return a+b+c;};};};console.log(fn(10)(20)(30));// 使用箭头函数简化:fn=a=>b=>c=>a+b+c;console.log(fn(10)(20)(30));
2.纯函数(不会用到自由变量)
// let dis=0.5;function getprice(price){return price*dis;};
纯函数
let dis=0.5;function getprice(price,dis){return price*dis;};console.log(getprice(100,dis));
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号