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

原来ES7~12分别添加了这些属性

时间:2023-03-28 12:33:22 HTML

ES6,又称ES2015,发布于2015年,此后每年都会增加一些新的属性,分别命名为ES7~12,发布年份对应2016年到2021年。ES7包含方法array,用于判断一个元素是否存在于数组中。在这个判断之前,indexOf是用来判断下标值的。如果小于0,则表示不存在。constlist=['alice','kiki','macus']console.log(list.includes('alice'))console.log(list.indexOf('alice'))console.log(list.includes('hello'))console.log(list.indexOf('hello'))includes返回一个布尔值,indexOf返回数组的下标索引ES7添加了索引操作的运算符,两个星号(**),在Before这个,Math.pow是用来计算constnum=3constsqrt=Math.pow(num,4)constresult=num**4console.log(sqrt,result)上面都是表示num的4次方,执行结果was81**operator通过babel编译成es5语法时,同样使用Math.powES8Object.values和Object.entriesObject.keys(ES6之前存在的属性)获取对象的所有键值,而Object.values获取对象value的所有值,Object.entries会返回一个包含每个key和value元素的数组constobj={name:'alice',age:18}constlist=['alice','kiki','macus']constmessage='hello'console.log(Object.keys(obj),Object.values(obj),Object.entries(obj))console.log(Object.keys(list),Object.values(list),Object.entries(list))console.log(Object.keys(messsage),Object.values(messsage),Object.entries(messsage))分别得到数组、对象和字符串的key和value以及key和value组成的stringPadding数组可以使用padStart和padEnd分别填充字符串的头部和尾部。输入填充字符串的长度和内容constmessage="helloworld"conststartMsg=message.padStart(15,'-')constendMsg=message.padEnd(16,'*')console.log(startMsg)console。log(endMsg)constnickName='Star'constfirstName=nickName.substr(0,1)constnewName=firstName.padEnd(nickName.length,'*')console.log(newName)用于字符串的开头和结尾分别是Padding和TrailingCommas尾随逗号的小case,允许函数在定义形参和传参时在最后一个参数后加一个逗号(,)functionfoo(a,b,){console.log(a,b,)}foo(1,2,)functionbaz(m,n){console.log(m,n)}baz('m','n',)最后一个参数后面加个逗号,就不会了是被认为是错误的写法getOwnPropertyDescriptors用于获取对象所有属性的描述constobj={name:'alice',age:18}console.log(Object.getOwnPropertyDescriptors(obj))包含是否可枚举(可枚举),可以Modify(writable),redefine(configurable)andvalueotherasyncandawait,这部分会放在下一篇详细记录所有ES9属性迭代器,这部分会放在下一篇详细记录spreadoperators,对象扩展运算符,记录在DoYouknowthesepropertiesinES6?本文中promisefinally,连同promise,将在后续文章中详细记录。ES10flat和flatMapflat用于数组降维。传入需要缩减的levelconst数组=[1,2,[3,4],[[5,6],[7,8],[9]],[10],11,11,11,[12、[13,[14]]]]constnum=array.flat(2)console.log(num)此时传入的降维级别为2,所以四维数组的数据有降维了两个,有两个维度flatMap的方法会先遍历数组,然后进行降维操作,相当于map+flatconstlist=["macusmogan","arishsira","lindakiki"]constresult=list.flatMap(item=>{constelement=item.split("")console.log('eachsplitelement:',element)returnelement})console.log(result)遍历时此时的每组元素,切割成Array,flatMap会直接降维Object.fromEntriesObject.fromEntries是将entries等数组类型转化为对象constobj={name:'alice',age:18}constarr=[‘alice’,‘kiki’,‘macus’]conststr=‘hello’constobjEntries=Object.entries(obj)constarrEntries=Object.entries(arr)conststrEntries=Object.entries(str)console.log(objEntries)console.log(Object.fromEntries(objEntries))console.log('------------------------------------------------------------')console.log(arrEntries)console.log(Object.fromEntries(arrEntries))console.log('-------------------------------------------------------------')console.log(strEntries)console.log(Object.fromEntriestries(strEntries))将对象、数组、字符串转为条目,再通过fromEntries转为对象。fromEntries不是Object.entries的反向操作,不会还原数组或字符串的类型。trimStarttrimEndtrim可用于去除首尾空格,ES10新增trimStarttrimEnd去除字符串首尾空格constmessage="helloworld"constmessageLen=message.lengthconsttrimMsg=message.trim()consttrimStartMsg=message.trimStart()consttrimEndMsg=message.trimEnd()控制台.log(messageLen)console.log(trimMsg,trimMsg.length)console.log(trimStartMsg,trimStartMsg.length)console.log(trimEndMsg,trimEndMsg.length)可以判断第一个和最后一个空格是否被去掉,其他Symbol的Desciptor属性在文章中有记录你知道ES6中的这些属性吗?可选的catch绑定,放在文章trycatchlater之前记录ES11bigInt表示大数可以使用Number.MAX_SAFE_INTEGER,但是如果需要计算这种表示方式,精度有问题。ES11增加了表示大数的方式,在数字后面写上字母n,比如1234567890987654321n但是在这种计算方式中,还是有一定的规律,带n的大数不能和不带n的小数运算。可以直接在小数后加n,也可以使用BigInt方法将小数转换为大数。constnum=Number.MAX_SAFE_INTEGERconsole.log(num+1)console.log(num+2)constbigNum=80082088208008208820nconsole.log(bigNum+10n)console,大数转小数可能会出现精度丢失的问题。log(bigNum+BigInt(10))console.log(Number(bigNum))上面的MAX_SAFE_INTEGER操作和bigInttoNumber存在精度损失的问题,如果null和undefined数据判断为false,则取运算符后的值,or运算符(||)对null、undefined、空字符串和0判断为falseconstnullStr=null;constundefinedStr=undefined;conststring="";constnumber=0;constuser={};console.log(nullStr??"不存在的内容",nullStr||"不存在的内容");console.log(undefinedStr??"UnrecognizedType",undefinedStr||"UnrecognizedType");console.log(string??"EmptyString",string||"EmptyString");console.log(number??"Number",number||"Number");console.log(user??"EmptyObject",user||"EmptyObject");两者只会在空字符串和数字0的情况下不一致。OptionalChiningOptional对象中使用链(?.)来判断数据的存在/可读性,只有不为null或undefined时,它会继续。constuser={name:'alice',favorite:{sport:'tennis'}}console.log(user?.favorite?.sport)console.log(user&&user.favorite&&user.favorite.sport)console.log(user?.info?.address)console.log(user&&user.info&&user.info.address)通过optionalchain和&&运算符达到同样的效果,但是代码更简洁globalThisjavascript代码可以运行在在浏览器或者nodejs中,这两个容器获取全局对象的方式不同。在浏览器中,可以使用window或者this,在node端,需要使用global。es11中统一,使用globalThis,无论浏览器端还是节点端都可以直接获取全局对象。console.log(globalThis)浏览器端打印window对象,node端打印global对象。其他用于标准化。es11之前没有要求forin遍历的key需要是key或者value,每个浏览器都有自己的实现,es11规定了标准,需要使用keyDynamicImport(动态导入),会记录下来在es模块文章Promise.allSettled中,会记录在promise文章importmeta中,在es模块文章中会记录ES12FinalizationRegistry,用于指定对象被垃圾回收器(GC)回收时的回调,以及通过registerletuser={name:"alice",};constregistry=newFinalizationRegistry((value)=>{console.log("对象被销毁",value);});registry.register(user,'user')user=nullGC时不时检查是否有可回收的垃圾,所以当对象指向null时,不会立即执行获取回调该函数在nodejs中无法测试,只能在浏览器,因为该进程将在之后关闭r在nodejs中执行,浏览器运行时是一个进程,不会关闭。WeakRef直接将对象A赋值给对象B,它们都指向一个内存地址0x100,因为此时是强引用,即使A指向null后,0x100仍然被B指向,所以0x100不会被销毁.如果想在A指向null后销毁0x100,可以使用weakRef实现弱引用。letuser={name:'alice'}letinfo=newWeakRef(user)constregistry=newFinalizationRegistry((value)=>{console.log("对象被销毁",value);});registry.register(user,'user')registry.register(info,'info')user=nullconsole.log(info,info.deref())通过new关键字创建弱引用,通过deref方法获取数据。当被引用对象被回收后,弱引用生成的对象将无法获取逻辑赋值运算符assignment逻辑运算,相当于逻辑运算后跟赋值运算||=逻辑or赋值运算,或者先运算,再赋值&&=逻辑与赋值运算,先与运算,再赋值??=逻辑空赋值运算,先判断空值,再赋值letnum=0//num=num+1等价于下面写num+=1console.log(num)letmessage=''//message=message||'hello'相当于下面的消息||='hello'console.log(message)letuser={name:'alice'}//user=user&&user.name相当于下面的写法user&&=user.nameconsole.log(user)letstr=0//str=str??'string'相当于下面的写法str??='string'console.log(str)逻辑赋值操作就像+=一样,就是在+1之后赋值。它是操作的语法糖。数字分隔符。较大的数字可以用下划线(_)分隔,以使代码更具可读性。constmomeny=100_200_300_400_500console.log(momeny)执行结果会去掉下划线,以十进制数据显示。replaceAllreplaceAll()方法返回一个新的字符串,新的满足模式(第一个参数)的字符串的所有部分都被替换为替换(第二个参数)constmessage="helloworld";console.log(message.replace("l","*"));console.log(message.replaceAll("l","*"));replaceAll会替换所有符合条件的,replace只会替换第一个或多个,这是ES7-12包含的大部分属性。关于js进阶,开发者需要掌握的东西还是很多的。可以看看我写的其他博文,持续更新中~