目录
ES7:
新特性
//1.Array.prototype.includes,用来检测数组中是否包含某个元素,返回布尔类型值。
const zy=['京大戟','祖师麻','香附'];
console.log(zy.includes('香附')); //true
console.log(zy.includes('花蕊石')); //false
//2.引入指数操作符**,用来实现幂运算,功能和结果与Math.pow相同。
console.log(2**10); //1024 ,Math.pow(2,10)
ES8:
async和await
async和await两种语法结合可以让异步代码像同步代码一样。
async函数:
1.async函数的返回值为promise对象
2.promise对象的结果由async函数执行的返回值决定
// async函数
async function fn(){
// 返回一个字符串
// return 'tml';
// 或return;
// --只要返回值的类型不是一个promise对象,返回的结果就都是一个成功的promise对象
// 除非抛出错误,返回结果是一个失败的promise
// throw new Error('出错');
// --返回值的类型如果是一个promise对象
// 返回成功(失败)的promise 则函数返回的也是成功(失败)的promise
return new Promise((resolve,reject)=>{
resolve('成功');
});
}
result=fn();
console.log(result);
await表达式:
1.await必须写在async函数中
2.await右侧的表达式一般为promise对象
3.await返回的是promise成功的值
4.await的promise失败了,就会抛出异常,需要通过try...catch捕获处理
// 创建promise对象
const p=new Promise((resolve,reject)=>{
resolve('成功');
// 如果失败
// reject('失败');
});
async function main(){
try {
let result=await p;
console.log(result);
} catch (e) {
console.log(e);
}
}
main();
读取文件实例:
const fs=require('fs');
function readText(){
return new Promise((resolve,reject)=>{
fs.readFile("./text.md",(err,data)=>{
if(err) reject(err);
resolve(data);
});
});
}
async function main(){
let text=await readText();
console.log(text.toString());
}
main();
发送AJAX请求:
// 发送AJAX请求,返回的结果是Promise对象
function sendAjax(url){
return new Promise((resolve,reject)=>{
// 创建对象
const x=new XMLHttpRequest();
// 初始化
x.open('GET',url);
x.send();
x.onreadystatechange=function(){
if(x.readyState===4){
if(x.status>=200 && x.status<300){
resolve(x.response);
}else{
reject(x.status);
}
}
}
});
}
// promise then方法测试
sendAjax("https://api.apiopen.top/getJoke").then(value=>{
console.log(value);
},reason=>{});
// async与await测试
async function main(){
let result=await sendAjax("https://api.apiopen.top/getJoke");
console.log(result);
}
main();
对象方法的扩展
1.Object.values()方法返回一个给定对象的所有可枚举属性值的数组
2.Object.entries()方法返回一个给定对象自身可遍历属性key,value的数组
3.Object.getOwnPropertyDescriptors()方法返回指定对象所有自身属性的描述对象。
const zy={
name:'中药',
kind:['五倍子','五味子','预知子'],
price:[12,23,34]
};
// 获取对象所有的键
console.log(Object.keys(zy));//["name", "kind", "price"]
// 获取对象所有的值
console.log(Object.values(zy));//["中药", Array(3), Array(3)]
// entries
console.log(Object.entries(zy));//输出:[Array(2), Array(2), Array(2)]
// 0: (2) ["name", "中药"]
// 1: (2) ["kind", Array(3)]
// 2: (2) ["price", Array(3)]
// length: 3
// 可以用来创建Map
const m=new Map(Object.entries(zy));
console.log(m.get('name'));//中药
// 对象属性的描述对象
console.log(Object.getOwnPropertyDescriptors(zy));//{name: {…}, kind: {…}, price: {…}}
// name: {value: "中药", writable: true, enumerable: true, configurable: true}
// kind: {value: Array(3), writable: true, enumerable: true, configurable: true}
// price: {value: Array(3), writable: true, enumerable: true, configurable: true}
// __proto__: Object
// 创建参数对象 中 第一个属性:原型对象;第二个属性:描述对象
const obj=Object.create(null,{
name:{
// 设置值
value:'tml',
// 属性特性
writable:true, //是否可写
configurable:true, //是否可删除
enumerable:true //是否可枚举
}
});
ES9:
扩展运算符与rest参数
rest参数与spread扩展运算符在ES6中已经引入,不过ES6中只针对数组。在ES9中为对象提供了像数组一样的rest参数和扩展运算符。
function connect({host,port,...user}){
console.log(host);
console.log(port);
console.log(user);
}
connect({
host:'127.0.0.1',
port:3306,
username:'root',
password:'123456',
type:'master'
});
// 127.0.0.1
// test1.html:15 3306
// test1.html:16 {username: "root", password: "123456", type: "master"}
const zy1={
t:'檀香'
}
const zy2={
j:'降香'
}
const zy3={
x:'仙茅'
}
const zy={...zy1,...zy2,...zy3};
console.log(zy);
// {t: "檀香", j: "降香", x: "仙茅"}
// t: "檀香"
// j: "降香"
// x: "仙茅"
// __proto__: Object
正则扩展:命名捕获分组
let str='<a href="http://127.0.0.1">localhost</a>';
// 提取URL与标签文本
const reg=/<a href="(.*)">(.*)<\/a>/;
const result=reg.exec(str);
console.log(result[1]);// http://127.0.0.1
console.log(result[2]);// localhost
//ES9 捕获分组(上面是以前的)
let str2='<a href="http://127.0.0.1">localhost</a>';
const reg2=/<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result2=reg2.exec(str2);
console.log(result2);
// (3) ["<a href="http://127.0.0.1">localhost</a>", "http://127.0.0.1", "localhost", index: 0, input: "<a href="http://127.0.0.1">localhost</a>", groups: {…}]
// 0: "<a href="http://127.0.0.1">localhost</a>"
// 1: "http://127.0.0.1"
// 2: "localhost"
// index: 0
// input: "<a href="http://127.0.0.1">localhost</a>"
// groups:
// url: "http://127.0.0.1"
// text: "localhost"
// length: 3
// __proto__: Array(0)
console.log(result2.groups.text); //localhost
正则扩展:反向断言
// 提取“111”
let str='TML1114今天下雨了111哈哈';
// 正向断言
const reg1=/\d+(?=哈)/;
const result1=reg1.exec(str);
console.log(result1);
// 反向断言
const reg2=/(?<=了)\d+/;
const result2=reg2.exec(str);
console.log(result2);
正则扩展:dotAll模式
// dot . 元字符 除换行以外的任意单个字符
let str=`
<ul>
<li>
<a>横经席</a>
<p>hengjingxi</p>
</li>
<li>
<a>黑三棱</a>
<p>heisanling</p>
</li>
</ul>`;
// const reg=/<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/;
// dotAll模式 g:全局匹配 模式修正符s
const reg=/<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs;
// const result=reg.exec(str);
let result;
let data=[];
while (result=reg.exec(str)) {
console.log(result);
data.push({name:result[1],pin:result[2]});
}
console.log(data);
// (2) [{…}, {…}]
// 0: {name: "横经席", pin: "hengjingxi"}
// 1: {name: "黑三棱", pin: "heisanling"}
// length: 2
// __proto__: Array(0)
ES10:
对象扩展方法
// 二维数组
const result=Object.fromEntries([
['name','黑老头'],
['type','中药']
]);
console.log(result); //{name: "黑老头", type: "中药"}
// Map
const m=new Map();
m.set('name','黑骨头');
const result2=Object.fromEntries(m);
console.log(result2); //{name: "黑骨头"}
// fromEntries与entries算是逆运算,前者将二维数组转换为对象,后者将对象转换为二维数组
字符串方法扩展
trimStart()清除字符串前端空白;trimEnd()清除字符串后端空白
let str=' tml ';
console.log(str); //" tml "
console.log(str.trimStart()); //"tml "
console.log(str.trimEnd()); //" tml"
数组方法扩展
// flat 将多维数组转低维数组,传递一个数字作为参数表示深度
const arr=[1,2,3,[4,5,[6,7]]];//三维数组
console.log(arr.flat());//[1, 2, 3, 4, 5, Array(2)]
console.log(arr.flat(2));//[1, 2, 3, 4, 5, 6, 7]
// flatMap
const arr2=[1,2,3];
const result=arr2.map(item=>[item*10]);//回调函数返回结果是数组
console.log(result);
// [Array(1), Array(1), Array(1)]
// 0: [10]
// 1: [20]
// 2: [30]
// 如果希望返回结果是一维数组
const result2=arr2.flatMap(item=>[item*10]);
console.log(result2);//[10, 20, 30]
Symbol扩展
// 获取Symbol的描述字符串
let s=Symbol('tml');
console.log(s.description);//tml
ES11:
私有属性
class Person{
// 公有属性
name;
// 私有属性
#age;
#weight;
// 构造方法
constructor(name,age,weight){
this.name=name;
this.#age=age;
this.#weight=weight;
}
intr0(){
console.log(this.name);
console.log(this.#age);
console.log(this.#weight);
}
}
// 实例化
const girl=new Person('tml',21,'50kg');
girl.intr0();//tml 21 50kg
Promise.allSettled
接收promise数组,返回结果是promise对象且都是成功的状态,结果的值是每一个promise的状态和结果
const p1=new Promise((resolve,reject)=>{
setTimeout(() => {
resolve('商品-1');
}, 1000);
});
const p2=new Promise((resolve,reject)=>{
setTimeout(() => {
// resolve('商品-2');
reject('出错了');
}, 1000);
});
// 调用allSettled
const result=Promise.allSettled([p1,p2]);
console.log(result); //返回结果都成功
// Promise {<pending>}
// __proto__: Promise
// [[PromiseStatus]]: "resolved"
// [[PromiseValue]]: Array(2)
// 0: {status: "fulfilled", value: "商品-1"}
// 1: {status: "rejected", reason: "出错了"}
// length: 2
// __proto__: Array(0)
// 调用all
const result2=Promise.all([p1,p2]);
console.log(result2); //返回结果失败
// Promise {<pending>}
// __proto__: Promise
// [[PromiseStatus]]: "rejected"
// [[PromiseValue]]: "出错了"
// ☒Uncaught (in promise) 出错了
String.prototype.matchAll
用来得到正则批量匹配的结果
let str=`
<ul>
<li>
<a>鹤虱风</a>
<p>heshifeng</p>
</li>
<li>
<a>和血丹</a>
<p>hexiedan</p>
</li>
</ul>`;
// 声明正则
const reg=/<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg;
const result=str.matchAll(reg);
console.log(result);//返回结果是一个可迭代对象
// RegExpStringIterator {}
// __proto__: RegExp String Iterator
// next: ƒ next()
// Symbol(Symbol.toStringTag): "RegExp String Iterator"
// __proto__: Object
for(let v of result){
console.log(v);
}
const arr=[...result];
console.log(arr);
// 对数据的批量提取十分有效
可选链操作符?.
应对对象类型的参数时使用,就不用对层级深的参数做层层的判断了
function main(config) {
// 原来:const dbHost=config && config.db && config.db.host;
// 可选链操作符 如果没有查找到会返回undefined,不会报错
const dbHost=config?.db?.host;
console.log(dbHost);//192.168.1.100
}
main({
db:{
host:'192.168.1.100',
username:'root'
},
cache:{
host:'192.168.1.200',
username:'admin'
}
});
动态import
可以按需加载
test1.html
<button id="btn">点击</button>
<script src="test2.js" type="module"></script>
test2.js
// 静态引入
// import *as m1 from "./test3.js";
const btn=document.getElementById('btn');
btn.onclick=function(){
// 动态引入
import('./test3.js').then(module=>{
module.hello();
});
};
test3.js
export function hello(){
alert('hello');
}
BigInt类型
let n=521n;
console.log(n,typeof(n));//521n "bigint" n表示大整型
// 将整型转换为大整型,注意:只能对整型数据进行操作,浮点型会报错
let n2=123;
console.log(BigInt(n2));
// 大数值运算
let max=Number.MAX_SAFE_INTEGER;
console.log(max); //9007199254740991
console.log(max+1);//9007199254740992
console.log(max+2);//9007199254740992 加更大的数值会无法计算
// 大整型只能与大整型进行运算,与整型运算会报错
console.log(BigInt(max)+BigInt(1)); //9007199254740992n
console.log(BigInt(max)+BigInt(2)); //9007199254740993n
console.log(BigInt(max)+BigInt(66));//9007199254741057n
绝对全局对象globalThis
console.log(globalThis);
// Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
(视频:B站尚硅谷)
457

被折叠的 条评论
为什么被折叠?



