【前端】ES11:ES11新特性
文章目录
1 Promise.allSettled
Promise.allSettled()方法返回一个在所有给定的promise都已经fulfilled或rejected后的promise,并带有一个对象数组,每个对象表示对应的promise结果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// Promise.all
function ajax(url){
return new Promise((resolve,reject)=>{
let xhr = new XMLHttpRequest()
xhr.open("get",url,true)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300){
resolve(JSON.parse(xhr.responseText))
}else{
reject(xhr.responseText)
}
}
}
})
}
//showloading
// Promise.allSettled成功和失败都会得到,弥补Promise.all的短板
// 过滤出fulfilled
Promise.allSettled([ajax("1.json"), ajax("2.json"), ajax("33.json")]).then(res=>{
//hideloading
console.log(res.filter(item=>item.status === "fulfilled"))
let res1 = res.filter(item=>item.status === "fulfilled")
console.log(res1.flatMap(item=>item.value.data)) // 拉平成一个数组
})
</script>
</body>
</html>
2 module新增
2.1 动态导入 import()
标准用法的import导入的模块是静态的,会使所有被导入的模块,在加载时就被编译(无法做到按需编译,降低首页加载速度)。
有些场景中,你可能希望根据条件导入模块或者按需导入模块,这时你可以使用动态导入代替静态导入。
动态导入返回promise对象。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="login">登录</button>
<script type="module">
function login(){
return "普通"
}
let obtn = document.querySelector("#login")
obtn.onclick = function(){
let role = login()
console.log(role)
render(role)
}
async function render(role){
if(role === "管理员"){
// 加载1.js
// let res1 = import("./1.js") // 返回promise对象, 需要.then才能拿到内容
let res1 = await import("./1.js") // 返回值promise对象
console.log(res1)
}else{
//加载2.js
let res2 = await import("./2.js")
console.log(res2)
}
}
// list = ["a.vue", "b.vue", "c.vue"]
/*
list.forEach(item=>{
import(item) // 导入文件,按需导入组件
})
*/
</script>
</body>
</html>
2.2 import.meta
import.meta会返回一个对象,有一个url属性,返回当前模块的url路径,只能在模块内部使用。
<script type="module">
import obj from './1.js'
</script>
//1.js
console.log(import.meta) // 当前模块所在的路径
export default {
}
2.3 export * as obj from ‘module’
//1.js
export default {
name:'111111'
}
export function test1(){
}
//2.js
export default {
name:"22222"
}
export function test2(){
}
export * as obj1 from './1.js'
//html
<script type="module">
import * as obj from './2.js'
console.log(obj)
</script>
3 字符串的 matchAll 方法
matchAll()方法返回一个包含所有匹配正则表达式的结果的迭代器。可以使用for…of遍历,或者使用展开运算符(…)或者Array.from转换为数组。
let str = `
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>
`
let reg = /<li>(.*)<\/li>/g
console.log(str.match(reg))
//'<li>1111</li>', '<li>2222</li>', '<li>3333</li>', '<li>4444</li>'
let str = `
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>
`
let reg = /<li>(.*)<\/li>/g
let match = null;
while(match = reg.exec(str)){
console.log(match[0])
console.log(match[1])
}
let str = `
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>
`
let reg = /<li>(.*)<\/li>/g
for(let i of str.matchAll(reg)){
console.log(i)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let str = `
<ul>
<li>11111</li>
<li>22222</li>
<li>33333</li>
<li>44444</li>
</ul>
`
let reg = /<li>(.*)<\/li>/g // 取出的内容带有<li></li>
console.log(str.match(reg))
let reg = /<li>(?<content>.*)<\/li>/g
//捕获exec
console.log(reg.exec(str))
console.log(reg.exec(str))
console.log(reg.exec(str))
console.log(reg.exec(str))
console.log(reg.exec(str))
let match = null
let list = []
while(match = reg.exec(str)){
console.log(match.groups.content)
list.push(match.groups.content)
}
console.log(list)
console.log(str.matchAll(reg)) // 迭代器
let iobj = str.matchAll(reg)
for(let i of iobj){
console.log(i.groups.content)
}
console.log([...iobj])
</script>
</body>
</html>
4 BigInt
JavaScript能够准确表示的整数范围在 -2^53 到 2^53 之间(不含两个端点),超过这个范围,无法精确表示这个值,这使得JavaScript不适合进行科学和金融方面的精确计算。
9007199254740992 //9007199254740992
9007199254740993 //9007199254740992
Math.pow(2,53) === Math.pow(2,53) + 1 //true
为了与Number类型区别,BigInt类型的数据必须添加后缀n
。
1234 // 普通整数
1234n // BigInt
// BigInt 的运算
1n + 2n // 3n
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log(2**53)
let num1 = 123
let num2 = 123n // BigInt
console.log(num1, num2)
console.log(num1 == num2) // true
console.log(num1 === num2) // false
console.log(BigInt(num1) === num2) // true
console.log(num2 > 100) // true
console.log(num2 < 200) // true
console.log(num2 + 2) // 报错
console.log(num2 + BigInt(2)) // 125n
//BigInt 函数
console.log(BigInt(2)) // 2n
console.log(BigInt(2**53)) // 9007199254740992n
console.log(BigInt(2**53) + BigInt(1)) // 9007199254740993n
console.log(BigInt(2**53) + BigInt(2))
console.log(BigInt(2**53) + BigInt(3))
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 自增长的id超大
let jsonstr = `
{
"id":9007199254740993,
"list":[]
}
`
// JSON.parse => JSON字符串转为JavaScript(对象)
console.log(JSON.parse(jsonstr).id) // 9007199254740992
// 1. 后端返回字符串 "9007199254740993"
//console.log(JSON.parse(jsonstr).id) // "9007199254740993"
// 2. 引入一个模块 json-bigint
/*
node环境
npm install json-bigint:依赖bignumber.js模块
生成node_modules文件夹
node .\index.js
*/
</script>
<!-- <script type="module"></script> -->
</body>
</html>
import JSONBigInt from 'json-bigint'
let JSONBigIntStr = JSONBigInt({ storeAsString: true }); // { storeAsString: true } 转为字符串
let JSONBigIntNative = JSONBigInt({ useNativeBigInt: true }); // { useNativeBigInt: true } 转为BigInt
let jsonstr = `
{
"id":9007199254740993,
"list":[]
}
`
console.log(JSONBigInt.parse(jsonstr)) // 对象类型
console.log(BigInt(JSONBigIntStr.parse(jsonstr).id)) // id转为字符串,再转为BigInt
//又提供了一种方案, 转为 BinInt
console.log(JSONBigIntNative.parse(jsonstr)) // 9007199254740993n
5 globalThis
globalThis提供了一个标准的方式来获取不同环境下的全局this对象(也就是全局对象自身)。
不像window或者self这些属性,它确保可以在有无窗口的各种环境下正常工作。所以,你可以安心的使用globalThis,不必担心它的运行环境。
为便于记忆,你只需要记住,全局作用域中的this就是globalThis。
// es6-shim:模拟低版本不存在的特性
var getGlobal = function () {
// the only reliable means to get the global object is
// Function('return this')()
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
var globals = getGlobal();
if (!globals.Reflect) {
defineProperty(globals, ‘Reflect’, {}, true);
}
//以前
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
let globals = getGlobal()
if (globals.document) {
console.log("进行dom操作相关")
} else {
console.log("不能进行dom操作")
}
//现在
if (globalThis.document) {
console.log("进行dom操作相关")
} else {
console.log("不能进行dom操作")
}
console.log(global === globalThis) // globalThis自动拿顶层对象,不必区分浏览器(window)、node(global)、webworker(self)
6 空值合并运算符
空值合并运算符(??)是一个逻辑运算符。
当左侧操作数为null或undefined时,其返回右侧的操作数,否则返回左侧的操作数。
let obj = {
name:"kerwin",
introduction:0
}
console.log(obj.introduction || "这个人很懒")
console.log(obj.introduction ?? "这个人很懒")
??和 || 的区别是什么呢?
他们两个最大的区别就是 ’ '和 0,??的左侧 为 ’ '或者为 0 的时候,依然会返回左侧的值。
|| 会对左侧的数据进行boolean类型转换,所以’ '和 0 会被转换成false,返回右侧的值。
<!--
* @作者: kerwin
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let str = null ?? "kerwin" // ??左边是null / undefined,返回??右边的值
let str1 = undefined ?? "kerwin" // "kerwin"
let str2 = "tiechui" ?? "kerwin" // "tiechui"
let str3 = 0 || "kerwin" // "kerwin"
let str4 = 0 ?? "kerwin" // 0
console.log(str)
let obj = {
name:"kerwin",
introduction:null
}
console.log(obj.introduction ?? "这个人很赖,什么也没有留下")
</script>
</body>
</html>
7 可选链操作符
可选链前面的值如果是null或undefined,则不再执行后面的,之前返回可选链前面的值。
let obj = {
name:"kerwin",
introduction:0,
// location:{
// city:"dalian"
// }
}
console.log(obj && obj.location && obj.location.city)
console.log(obj?.location?.city)
原文地址:https://blog.csdn.net/weixin_45980065/article/details/142497778
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!