本文为个人总结使用
ES7(ECMAScript 2016)新特性
1. 数组包含方法 includes
使用
数组的元素包含判定
let arr = ['a','b','c']
arr.includes('a') //true
arr.includes('d') //false
//第二个参数是 fromIndex ,
//如果`fromIndex`为负值,使用`数组长度 + fromIndex`计算出的索引作为新的`fromIndex`,
//如果新的`fromIndex`为负值,则搜索整个数组。
arr.includes('a',0) //true
arr.includes('a',1) //false
arr.includes('a',-3) //true
对象除本身外返回false,NaN本身也返回false
es5手写实现
Array.prototype.includes1= function(item,index){
if(isNaN(index)){
index= 0
}else{
index = parseInt(index)
}
if(index < 0){
index = this.length + index
}
if(index < 0){
index = 0
}
for (let i = index; i < this.length; i++) {
if( typeof this[i] =='number' &&isNaN(this[i])&& typeof item =='number' &&isNaN(item)){
return true
}else if(this[i]===item){
return true
}
}
return false
}
注意:
- 区分 isNaN 和 Number.isNaN
- es5 filter或者indexOf,es6 中some every方法也可以实现不过要注意NaN
2. 幂运算符号 **
数字的幂运算符号
使用
2*3**2 // 2*(3*3) = 18
es5手写实现
由于JS中并不支持自定义运算符,所以无法进行手写实现,不过es5中存在相同的计算函数Math.pow
Math.pow(2,3) //8
注意:
- js中 ^ 是二进制位异或运算符,不要混淆!
2^3 //1 - &(与运算)、|(或运算)、~(取反运算)、^(异或运算)、<< >>(位移运算符)