ES7+ 新特性
Opened this issue · 0 comments
machao07 commented
一、ES7(ES2016)
1、Array.prototype.includes 是查找一个值在不在数组里(有-true,无-false
)
let arr = [1, 2, 3]
arr.includes(3) // true
// `等同于:indeOf(有-返回下标,无-返回-1)`
arr.indexOf(3) > -1 // true
indexOf 缺点:
1、不够语义化,要先找到参数值的第一个出现位置,所以要去比较是否不等于-1
2、内部使用严格相等运算符(===)进行判断,这会导致对NaN的误判
[NaN].indexOf(NaN)// -1
2、 求幂运算符(**)
let a = 7 ** 2
等同于:
Math.pow(7,2)
console.log(a === Math.pow(7,2)) // true
二、ES8(ES2017)
1、Async/Await
场景需求:
需要先请求a链接,等返回信息之后,再请求b链接的另外一个资源。
- fetch请求实现
fetch被定义在window对象中,它返回的是一个Promise对象
fetch('https://blog.csdn.net/')
.then(response => {
console.log(response)
return fetch('https://juejin.im/')
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
- async/await
- 还支持
try...catch
来捕获异常- await 不可以脱离 async 单独使用,await 后面一定是Promise 对象,如果不是会自动包装成Promise对象
async function foo () {
try {
let response1 = await fetch('https://blog.csdn.net/')
let response2 = await fetch('https://juejin.im/')
} catch (err) {
console.error(err)
}
}
foo()
async是一个通过异步执行并隐式返回Promise作为结果的函数。
async function foo () {
return '浪里行舟'
}
foo().then(val => {
console.log(val) // 浪里行舟
})
2、Object.values(),Object.entries()
- ES5 引入了
Object.keys
方法,返回一个数组所有健名。- ES8 引入
Object.values
和Object.entries
Object.values
方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值。
const obj = { foo: 'bar', baz: 42 };
Object.values(obj) // ["bar", 42]
const obj = { 100: 'a', 2: 'b', 7: 'c' };
Object.values(obj) // ["b", "c", "a"]
如果属性名为数值的属性,是按照数值大小,从小到大遍历的,因此返回的顺序是b、c、a。
Object.entries()
方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的 键值对数组。这个特性我们后面介绍ES10的Object.fromEntries()还会再提到。
const obj = { foo: 'bar', baz: 42 };
Object.entries(obj) // [ ["foo", "bar"], ["baz", 42] ]
const obj = { 10: 'xxx', 1: 'yyy', 3: 'zzz' };
Object.entries(obj); // [['1', 'yyy'], ['3', 'zzz'], ['10': 'xxx']]
3.String padding(padStart、padEnd
)
targetLength
(必填):当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身。padString
(可选):填充字符串。如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断,此参数的缺省值为 " "。
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
三、ES9(ES2018)
1、for await of
2、Object Rest Spread(...扩展运算符)
ES6中spread操作符
(...)
替换cancat()和slice()方法,使数组的操作(复制、合并)
const arr1 = [10, 20, 30];
const copy = [...arr1]; // 复制
console.log(copy); // [10, 20, 30]
const arr2 = [40, 50];
const merge = [...arr1, ...arr2]; // 合并
console.log(merge); // [10, 20, 30, 40, 50]
ES9通过向对象文本添加扩展属性进一步扩展了这种语法。他可以将一个对象的属性拷贝到另一个对象上(浅拷贝)
const input = { a: 1, b: 2}
const output = { ...input, c: 3}
input.a='浪里行舟'
console.log(input, output)
// {a: "浪里行舟", b: 2}
// {a: 1, b: 2, c: 3}
四、ES10(ES2019)
1、多维数组转换
Array.prototype.flat()
Array.prototype.flatMap()
flat 创建一个新数组,其中所有子数组元素递归连接到该数组中,直到指定的深度。默认深度为1
const arr1 = [1, 2, [3, 4]]
arr1.flat() // [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]]
arr2.flat() // [1, 2, 3, 4, [5, 6]]
const arr3 = [1, 2, [3, 4, [5, 6]]]
arr3.flat(2) // [1, 2, 3, 4, 5, 6]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]
arr4.flat(Infinity) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2、 Object.fromEntries()
键值对转换成对象
const entries = new Map([
['apple', 'origin'],
['grapes', 'peach']
])
Object.fromEntries(entries)
// {apple: 'origin', grapes: 'peach'}
五、ES11(ES2020)
1、可选链 ( ?. )
var name = user && user.info && user.info.name;
var age = user && user.info && user.info.getAge && user.info.getAge();
可简写为:
var name = user?.info?.name;
var age = user?.info?.getAge?.();
2、空值合并运算符( ?? )
如果没有该属性就会设置一个默认的值
var level = (user.data && user.data.level) || '暂无等级';
简写为:
var level = `${user.data.level}级`?? '暂无等级';
与 可选链 相结合
var level = user.data?.level ?? '暂无等级';
注区别:
"" ?? true // ""
"" || true // true
"" ?? false // ""
"" || false // false
"" ?? null // ""
"" || null // null
??
只能作用于undefined
和null
六、ES12(ES2021)
1、String.prototype.replaceAll
const str = "hello world";
str.replace(/o/g, "a") // "hella warld"
str.replaceAll("o", "a") // "hella warld"
2、Promise.any
3、数字分隔符 _
const sixBillion = 6000_000_000
console.log(sixBillion) // 6000000000
const sum = 1000 + 6000_000_000
console.log(sum) // 6000001000
4、新增逻辑赋值操作符
??=
、&&=
、||=
a??=b
// 等价于: a = a ?? b
// a = (a === null||a === undefined) ? b : a
a||=b
// 等价于:a = a || b
// a = a ? a : b
a&&=b
// 等价于:a = a && b
// a = a ? b : a
七、ES13(ES2022)
1、判断对象属性( Object.hasOwn )
- 替代
in
操作符,过滤原型链/object.create
的属性- 替代
obj.hasOwnProperty
,Object.create(null)
不继承原型链的属性和方法,{}
继承
// in、Object.prototype、Object.create
const Person = function (age) {
this.age = age
}
Person.prototype.name = 'fatfish'
const p1 = new Person(24)
const p2 = Object.create({sex: '女'})
console.log('name' in p1) // true
console.log(Object.hasOwnProperty(p1, 'name')) // false
console.log(Object.hasOwn(p1, 'name')) // false
console.log('sex' in p2) // true
console.log(Object.hasOwnProperty(p2, 'sex'))
console.log(Object.hasOwn(p2, 'sex'))
// hasOwnProperty
let object = { age: 24 }
let object2 = Object.create({ age: 24 })
Object.hasOwnProperty(object2, 'age') // true
Object.hasOwn(object2, 'age') // false