ES7(2016)
新增了兩個新特性:
1. 數組includes()方法,用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回true,否則返回false。
2. a ** b指數運算符,它與 Math.pow(a, b)相同。
1.Array.prototype.includes()
includes()
函數用來判斷一個數組是否包含一個指定的值,如果包含則返回 true
,否則返回false
。
includes
函數與 indexOf
函數很相似,下面兩個表達式是等價的:
arr.include(x) //等價於 arr.indexOf(x)>=0
接下來我們來判斷數字中是否包含某個元素:
在ES7之前的做法
使用indexOf()
驗證數組中是否存在某個元素,這時需要根據返回值是否為-1來判斷:
let arr = ['react', 'angular', 'vue']; if (arr.indexOf('react') !== -1) { console.log('react存在'); }
使用ES7的includes()
使用includes()驗證數組中是否存在某個元素,這樣更加直觀簡單:
let arr = ['react', 'angular', 'vue']; if (arr.includes('react')) { console.log('react存在'); }
2.指數操作符
在ES7中引入了指數運算符**
,**
具有與Math.pow(..)
等效的計算結果。
不使用指數操作符
使用自定義的遞歸函數calculateExponent或者Math.pow()進行指數運算:
function calculateExponent(base, exponent) { if (exponent === 1) { return base; } else { return base * calculateExponent(base, exponent - 1); } } console.log(calculateExponent(2, 10)); // 輸出1024 console.log(Math.pow(2, 10)); // 輸出1024
使用指數操作符
使用指數運算符**,就像+、-等操作符一樣:
console.log(2**10);// 輸出1024