ES7-ES12知识点浅析
1、ES7
1、Array Inculdes
//ES7之前
const names = ['abc', 'cba', 'nba', 'mba', NaN];
if (names.indexOf('cba') !== -1) {
console.log('包含abc元素');
}
//是否包含cba,第二个参数时从第几个下标开始,包括开始的下标
if (names.includes('cba', 2)) {
console.log('包含abc元素');
}
//indexOf和includes判断NAN
//indexOf无法判断是否存在NAN
const names = ['abc', 'cba', 'nba', 'mba', NaN];
if (names.indexOf(NaN) !== -1) {
console.log('包含NaN');
}
if (names.includes(NaN)) {
console.log('包含NaN');
}
2、指数运算符
//ES7之前
const result1 = Math.pow(3, 3);
// ES7: **
const result2 = 3 ** 3;
console.log(result1, result2);
2、ES8
1、Object values
通过Object.keys 获取一个对象所有的key,在ES8中提供了Object.values 来获取所有的value值;
const obj = {
name: 'byj',
age: 18,
};
console.log(Object.keys(obj));
console.log(Object.values(obj));
//[ 'name', 'age' ]
//[ 'byj', 18 ]
//其他情况
//传入数组获取数组本身,传入字符串获取每一个字符
console.log(Object.values(['abc', 'cba', 'nba']));
console.log(Object.values('abc'));
//[ 'abc', 'cba', 'nba' ]
//[ 'a', 'b', 'c' ]
2、Object entries
获取到一个数组,数组中会存放可枚举属性的键值对数组。
const obj = {
name: 'byj',
age: 18,
};
console.log(Object.entries(obj));//[ [ 'name', 'byj' ], [ 'age', 18 ] ]
//遍历key和value
const obj = {
name: 'byj',
age: 18,
};
const objEntries = Object.entries(obj);
objEntries.forEach(item => {
console.log(item[0], item[1]);
});
//name byj
//age 18
console.log(Object.entries(['abc', 'cba', 'nba'])); //[ [ '0', 'abc' ], [ '1', 'cba' ], [ '2', 'nba' ] ]
console.log(Object.entries('abc'));//[ [ '0', 'a' ], [ '1', 'b' ], [ '2', 'c' ] ]
3、String Padding
填充字符串实现格式化效果,ES8中增加了padStart 和padEnd 方法,分
别是对字符串的首尾进行填充的。
const message = 'Hello World';
// 第一个参数:填充长度,第二个参数:用于填充的内容
const newMessage = message.padStart(15, '*').padEnd(20, '-');
console.log(newMessage);//****Hello World-----
//场景
const cardNumber = '321324234242342342341312';
const lastFourCard = cardNumber.slice(-4);
const finalCard = lastFourCard.padStart(cardNumber.length, '*');
console.log(finalCard); //********************1312
4、Trailing Commas
结尾逗号,允许在函数定义和调用时多加一个逗号,这个在编辑器格式化的时候会自动去除,了解即可。
function foo(m, n,) {}
foo(20, 30,)
5、Object Descriptors
获取对象的所有属性描述符
const obj = {
name: 'byj',
age: 18,
};
console.log(Object.getOwnPropertyDescriptors(obj));
// {
// name: {
// value: 'byj',
// writable: true,
// enumerable: true,
// configurable: true
// },
// age: { value: 18, writable: true, enumerable: true, configurable: true }
// }
6、async和await
通过async将函数定义为异步函数。
async和await涉及的知识点较多,浅析不详细扩展
3、ES9
1、Async iterators
涉及知识点较多,浅析不详细扩展
2、Object spread operators:
对象展开运算
const obj = { name: 'byj' };
const newObj = { ...obj };
//是浅拷贝
3、Promise finally
涉及知识点较多,浅析不详细扩展
4、ES10
1、flat flatMap
- flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
- flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。
- 注意一:flatMap是先进行map操作,再做flat的操作;
- 注意二:flatMap中的flat相当于深度为1;
// 1.flat的使用
const nums = [
10,
20,
[2, 9],
[
[30, 40],
[10, 45],
],
78,
[55, 88],
];
//默认降为深度为1,即二维数组转为一维数组
const newNums = nums.flat();
console.log(newNums); //[ 10, 20, 2, 9, [ 30, 40 ], [ 10, 45 ], 78, 55, 88 ]
const newNums2 = nums.flat(2);
console.log(newNums2);//[10, 20, 2, 9, 30, 40, 10, 45, 78, 55, 88];
// 2.flatMap的使用
const nums2 = [10, 20, 30];
const newNums3 = nums2.flatMap(item => {
return item * 2;
});
const newNums4 = nums2.map(item => {
return item * 2;
});
console.log(newNums3);//[ 20, 40, 60 ]
console.log(newNums4);//[ 20, 40, 60 ]
//flatmap应用场景,将单词分隔后再扁平化
const messages = ['Hello World', 'hello lyh', 'my name is byj'];
const words = messages.flatMap(item => {
return item.split(' ');
});
console.log(words);//['Hello', 'World', 'hello', 'lyh', 'my', 'name', 'is', 'byj'];
2、Object fromEntries
Object.entries 将一个对象转换成entries,Object.formEntries将entries转化为对象
const obj = {
name: 'byj',
age: 18,
};
const entries = Object.entries(obj);
console.log(entries);
// 通过遍历将entries转化为object对象
// const newObj = {};
// for (const entry of entries) {
// newObj[entry[0]] = entry[1];
// }
// 1.ES10中新增了Object.fromEntries方法
const newObj = Object.fromEntries(entries);
console.log(newObj);
//应用场景
// 将query转成key:value的对象格式
const queryString = 'name=byj&age=18';
const queryParams = new URLSearchParams(queryString);
for (const param of queryParams) {
console.log(param);
}
const paramObj = Object.fromEntries(queryParams);
console.log(paramObj);//{ name: 'byj', age: '18' }
3、trimStart trimEnd
去除字符串首尾空格通过trim方法,单独去除前面和后面使用trimStart trimEnd
const message = ' Hello World ';
console.log(message.trim());//Hello World
console.log(message.trimStart());//Hello World
console.log(message.trimEnd());// Hello World
4、Symbol description
获取创建Symbol时传入的value
5、Optional catch binding
涉及知识点较多,浅析不详细扩展
5、ES11
1、BigInt
- 在早期的JavaScript中,我们不能正确的表示过大的数字:
- 大于MAX_SAFE_INTEGER的数值,表示的可能是不正确的。
const maxInt = Number.MAX_SAFE_INTEGER;
console.log(maxInt); // 9007199254740991
console.log(maxInt + 1);//9007199254740992
console.log(maxInt + 2);//9007199254740992
- ES11中,引入了新的数据类型BigInt,用于表示大的整数:
- BitInt的表示方法是在数值的后面加上n
// ES11之后: BigInt
const bigInt = 900719925474099100n;
// 运算过程中需要相同数据类型
console.log(bigInt + 10n);
const num = 100;
console.log(bigInt + BigInt(num));
// 转化为number类型,可能存在安全性
const smallNum = Number(bigInt);
console.log(smallNum);
2、Nullish Coalescing Operator
空值合并操作符,判断是否有值,代替逻辑或
//之前写法,逻辑或
//弊端:如果foo是空字符串或是0,既不是undefined或null,如果希望拿到空字符串或是0就会导致bug
const foo = undefined;
const bar = foo || 'defualt value';
console.log(bar); //defualt value
//空值合并运算符替代写法,只有foo为undefined或者为null才会使用后面的值
const foo = undefined;
const bar = foo ?? 'defualt value';
console.log(bar); //defualt value
3、Optional Chaining
可选链操作符,主要作用是让我们的代码在进行null和undefined判断时更加清晰和简洁
const info = {
name: 'll',
// friend: {
// girlFriend: {
// name: "hmm"
// }
// }
};
// console.log(info.friend.girlFriend.name); //TypeError: Cannot read property 'girlFriend' of undefined
// 假定info肯定有,如果不确定friend是否存在,如果不存在后面代码直接不执行返回undefined
console.log(info.friend?.girlFriend?.name); //undefined
4、Global This
- 希望获取JavaScript环境的全局对象,不同的环境获取的方式是不一样的
- 在浏览器中可以通过this、window来获取;
- 在Node中我们需要通过global来获取;
- 获取全局对象进行了统一的规范:globalThis
// 在浏览器下
// console.log(window)
// console.log(this)
// 在node下
// console.log(global)
// ES11
console.log(globalThis);
5、for…in标准化
通过for in遍历对象的key
const obj = {
name: 'byj',
age: 18,
};
for (const item in obj) {
console.log(item); //name age
}
6、Dynamic Import
涉及知识点较多,浅析不详细扩展
7、Promise.allSettled
涉及知识点较多,浅析不详细扩展
8、import meta
涉及知识点较多,浅析不详细扩展
6、ES12
1、FinalizationRegistry类
const finalRegistry = new FinalizationRegistry(value => {
// 注册的对象被销毁时执行的回调函数
console.log('注册在finalRegistry的对象, 某一个被销毁', value);
});
let obj = { name: 'byj' };
let info = { age: 18 };
// 第一个参数:注册的对象,第二个参数:传入的value
finalRegistry.register(obj, 'obj');
finalRegistry.register(info, 'value');
obj = null;
info = null;
2、WeakRefs
- 我们默认将一个对象赋值给另外一个引用,那么这个引用是一个强引用
- 如果我们希望是一个弱引用的话,可以使用WeakRef
3、logical assignment operators
1、逻辑或赋值 ||=
//||的升级版,值为undefined或者为null或者为空字符串或者0
let message = 'hello world';
message = message || 'default value';
message ||= 'default value';
console.log(message);
2、逻辑与赋值 &&=
//&&的升级版,一般用不到
let info = {
name: 'byj',
};
// 1.判断info
// 2.有值的情况下, 取出info.name并赋值
// info = info && info.name
info &&= info.name;
console.log(info);
3、逻辑空赋值 ??=
//??的升级版
//只有值为undefined或者为null
let message = 0;
message ??= 'default value';
console.log(message); //0
4、Numeric Separator
_下划线数字分隔符