教程 > ES6 教程 > ES6 高级 阅读:19

ES7 新特性

本章提供有关 ES7 中新功能的知识。


指数运算符

ES7 引入了一种新的数学运算符,称为求幂运算符。 此运算符类似于使用 Math.pow() 方法。 求幂运算符由双星号 ** 表示。 该运算符只能用于数值。 使用求幂运算符的语法如下

语法

求幂运算符的语法如下所述

base_value ** exponent_value

示例

以下示例使用 Math.pow() 方法和求幂运算符计算数字的指数。

let base = 2
let exponent = 3
console.log('using Math.pow()',Math.pow(base,exponent))
console.log('using exponentiation operator',base**exponent)

上面代码片段的输出如下

using Math.pow() 8
using exponentiation operator 8

数组 include

ES7 中引入的 Array.includes() 方法有助于检查数组中的元素是否可用。 在 ES7 之前,可以使用 Array 类的 indexof() 方法来验证数组中是否存在一个值。 如果找到数据,indexof() 返回数组中第一个出现的元素的索引,如果数据不存在,则返回 -1。

Array.includes() 方法接受一个参数,检查作为参数传递的值是否存在于数组中。 如果找到该值,则此方法返回 true,如果该值不存在,则返回 false。 使用 Array.includes() 方法的语法如下:

Array.includes(value)

或者

Array.includes(value,start_index)

第二种语法检查指定索引中是否存在该值。

示例

下面的示例声明一个数组标记并使用 Array.includes() 方法来验证数组中是否存在值。

let marks = [50,60,70,80]
// 检查数组中是否包含 50
if(marks.includes(50)){
    console.log('found element in array')
}else{
    console.log('could not find element')
}

// 检查是否从索引 1 中找到 50
if(marks.includes(50,1)){ //search from index 1
    console.log('found element in array')
}else{
    console.log('could not find element')
}

// 检查数组中的不是数字(NaN)
console.log([NaN].includes(NaN))

// 创建对象数组
let user1 = {name:'kannan'},
user2 = {name:'varun'},
user3={name:'prijin'}
let users = [user1,user2]

// 检查对象在数组中可用
console.log(users.includes(user1))
console.log(users.includes(user3))

上述代码的输出如下结果

found element in array
could not find element
true
true
false

查看笔记

扫码一下
查看教程更方便