ES7新特性

ES6是多年来JavaScript的重大版本变革,深受开发者的欢迎。

ES6就是ES2015,也就是从此时开始,JavaScript变为每年更新一次,按年计算依次类推。ES7(2016年)、ES8(2017年)、ES9(2018年)。

除了ES6更新幅度较大之外,后面的几次更新较小。了解起来也比较容易。

ES7

ES7在ES6的基础上添加了三个内容:求幂运算符(**)、Array.prototype.includes()方法以及函数作用域中严格模式的变更。

1、求幂运算符(**)

console.log( 3**2 )  // 9
// 相当于 数学方法 Math.pow(3, 2)

使用起来更简洁。

2、Array.prototype.includes() 方法

此方法是判断一个元素是否在数组中,返回一个布尔值,true或者false。该方法只能判断一些简单类型的数据,复杂类型则无法判断。和indexOf方法作用类似。

该方法接受两个参数,第一个就是要判断的数据,第二个是开始位置的索引值。

 1 let arr1 = [1, 2, 3, 'tom', 'jerry'];
 2 let arr2 = [1, [2, 3], 4];
 3 let arr3 = [{name: 'tom'}, {name: 'jerry'}, {age: 24}];
 4 
 5 console.log( arr1.includes(1) )             // true
 6 console.log( arr1.includes(1, 1) )             // false  从下标为1的开始
 7 console.log( arr1.includes('tom') )         // true
 8 console.log( arr2.includes([2, 3]) )        // false
 9 console.log( arr3.includes({name: 'tom'}) ) // false
10 console.log( arr1.indexOf(1) )             // 0
11 console.log( arr1.indexOf('tom') )         // 3
12 console.log( arr2.indexOf([2, 3]) )        // -1
13 console.log( arr3.indexOf({name: 'tom'}) ) // -1

与indexOf的优劣:如果只是判断某元素是否存在于数组中,includes 方法更好些,因为是返回的布尔值可以直接拿来判断使用。

如果想要判断是否存在于数组中并且想要获取该元素的下标,则 indexOf方法更好些。

还有一点:就是对 NaN 的判断:

1 let arr4 = [1, 2, NaN];
2 console.log( arr4.indexOf(NaN) )    // -1
3 console.log( arr4.includes(NaN) )   // true

 

posted @ 2019-08-27 22:26  我的故事没编好  阅读(740)  评论(0编辑  收藏  举报