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

ES6语法百科

时间:2023-04-05 01:43:49 HTML5

做一个小程序,需要用到ES6语法,所以我做一个总结。有些东西可能还不够完整,我暂时总结一下。以后补充1.variableletlocalvariableconstconstantvarglobalvariable2.stringextensionletstr="123"str.includes("1")//trueincludes方法是否包含str.startsWith("2")//false是否以2开头str.endsWith("2")//false是否以2结尾3.解构表达式//数组解构letarr=[1,2,3]const[x,y,z]=arr;//x,y,z对应1,2,3//对象解构constperson={name:"jack",age:21,language:['java','php'],}let{name,age,language}=person//自定义命名let{name:n,age:a,language}=person4.Functionoptimization//参数=1上面的优化,意思是当b没有值时,默认为1functiontest(a,b=1){console.log(a+b)}5.箭头函数//Demo1单参数vardemo1=fucntiondemo1(obj){console.log(obj)}箭头函数简化为:vardemo1=obj=>console.log(obj);//Demo2两个参数varsum=function(a,b){console.log(a+n)}箭头函数简化为:varsum=(a,b)=>console。log(obj);//Demo3没有参数letsayHello=()=>console.log("hello!");//Demo4代码使用多行{}varsum=(a,b)=>{console.log(a+n);console.log(a+n)}//Demo5对象函数缩写letperson={name:"jeck";//原文eat:function(food){console.log(this.name+food)}//箭头函数eat2:food=>console.log(this.name+food)//简化版eat3(food){console.log(this.name+food)}}//Demo6:带解构表达式的箭头函数letperson={name:"jeck";eat2:food=>控制台。log(this.name+food)}functiontest1(person){console.log(person.name);}//简化调用函数使用{}传参,传入对象vartest1=({name})=>console.log(name);test1(person);6.map和reduce函数map让原始集合由map中的函数处理回调letarr=['1','2','3'];arr.map(s=>parseInt(s))//将字符串转为内证书//reduce()接收一个函数和一个初始值,当第一个参数是上一个reduce的处理结果时第二个参数是数组中要处理的下一个元素constarr=[1,20,30,40]arr.reduce((a,b)=>a+b)7.展开运算符(三个点...)将数组转换为逗号分隔的参数序列functionadd(a,b){returna+b;}varnumber=[1,2];//数组合并vararrs=[...[1,2,3],...[4,5,6]];//[1,2,3,4,5,6]//将字符串转为数组console.log([...'hello'])//['h','e','l','l','o']8.promise函数格式constpromise=newpromise(function(resolve,reject){//operation//if(success){resolve(value);//success}else{reject(error)//failure}})//执行并执行一些东西promise.then(function(value){//异步回调}).catch(function(error){//异常回调})9.set和mapset只能保存不同的元素,相同的元素会被忽略map对象letset=newset();letset=newset([2,3,4,5]);//map接受一个数组,数组中的元素是键值对letmap=newmap([['key','value'],function(){//外汇返利www.fx61.com['key1','value1'],])10.for.of循环for(letobjofh){console.log(obj)}11.模块化导出importexport导出命令calssUtil{sum=(a,b)=>a+b;}exportdefaultUtilimportimportUtilfrom'./Util'