发布时间:2016年6月 ES7 是最小的一个版本,仅新增了2个特性。
1. Array.prototype.includes()
判断数组中是否包含指定元素,返回 true 或 false。
语法
arr.includes(valueToFind[, fromIndex])
基本用法
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(1, 1); // false,从索引1开始搜索
[1, 2, 3].includes(3, -1);// true,负数从末尾计算
对比 indexOf
// indexOf 返回索引,找不到返回 -1
[1, 2, 3].indexOf(2); // 1
[1, 2, 3].indexOf(4); // -1
// includes 返回布尔值,语义更清晰
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
处理 NaN 的优势
// indexOf 无法正确判断 NaN
[NaN].indexOf(NaN); // -1
// includes 可以正确判断 NaN
[NaN].includes(NaN); // true
在 if 条件中使用
// 旧写法
if (arr.indexOf(item) !== -1) {
// 找到了
}
// 新写法,更简洁
if (arr.includes(item)) {
// 找到了
}
注意事项
- 只能判断简单类型和 NaN,对象引用需要 === 匹配
- 对
undefined也能正确判断
[1, undefined, 3].includes(undefined); // true
let obj = { a: 1 };
let arr = [obj];
arr.includes(obj); // true
arr.includes({ a: 1 }); // false,不同引用
2. 指数运算符 **
** 是一个新的数学运算符,用于计算幂运算,等价于 Math.pow()。
基本用法
// 旧写法
Math.pow(2, 10); // 1024
// 新写法
2 ** 10; // 1024
负数底数
(-2) ** 2; // 4
(-2) ** 3; // -8
注意:不能一元运算符连用
// 语法错误,不能直接对负数使用
-2 ** 2; // SyntaxError
// 需要加括号
(-2) ** 2; // 4
-(2 ** 2); // -4
结合赋值运算符 **=
let a = 2;
a **= 3; // a = 8,等同于 a = a ** 3
let b = 5;
b **= 0; // b = 1
let c = 3;
c **= -2; // c = 0.111...,等同于 3 的 -2 次方
实际应用场景
// 面积计算
let r = 5;
let area = Math.PI * r ** 2; // 圆面积
// 文件大小单位转换
let bytes = 1024;
let kb = bytes ** 2; // 1,048,576(1MB)
let mb = bytes ** 3; // 1,073,741,824(1GB)
// 二进制转十进制
2 ** 8; // 256
总结
| 特性 | 说明 | 用途 |
|---|---|---|
Array.prototype.includes() | 判断数组是否包含某元素 | 替代 indexOf 做存在性检查 |
** 指数运算符 | 幂运算简写 | 替代 Math.pow() |
ES7 虽然只新增了2个特性,但都非常实用,在日常开发中使用频率很高。