ECMA 2016(ES7)新特性

本章内容:

  • Array.prototype.includes():判断一个数组是否包含一个指定的值,如果包含则返回 true,否则返回 false。
  • 幂运算符**: a ** b 指数运算符,它与 Math.pow(a, b)相同。

Array.prototype.includes()

includes() 函数用来判断一个数组是否包含一个指定的值,如果包含则返回 true,否则返回false

includes 函数与 indexOf 函数很相似,下面两个表达式是等价的:

语法

arr.includes(valueToFind[, fromIndex])

使用

接下来我们来判断数字中是否包含某个元素:

const arr = ["a", "b", "c", "d", "e", "f"];
arr.includes("c"); // true
arr.includes("c", 1); // true
arr.includes("c", 3); // true
// fromIndex 参数值也可以为负数,那样从倒数第N个位置开始搜索指定的值。
arr.includes("c", -3); // false
arr.includes("c", -4); // true

在 ES7 之前只能通过indexOf()验证数组中是否存在某个元素(返回-1 表示不存在)

指数操作符

具有与Math.pow(..)等效的计算结果。

示例

2 ** 2; // 4
3 ** 2; // 9
2 ** 2.5; // 5.65685424949238
// a ** b ** c 等同于 a ** (b ** c)
2 ** 3 ** 2; // 512
2 ** (3 ** 2); // 512
(2 ** 3) ** 2; // 64
// 负数使用`**`前先加小括号
(-2) ** 3; // -8
-2 ** 3; // SyntaxError: Unexpected

注意任何数字,包括 NaN,它的 0 次幂都是 1。

如果指数是 NaN,结果总是 NaN,无论底数是什么。


posted @ 2024-05-22 15:20  _zhiqiu  阅读(69)  评论(0编辑  收藏  举报