JavaScript - ES6 的新增功能特性
JavaScript 的 ES6 版本于 2015 年发布,标志着 JavaScript 的第二次重大修订。ES6 也称为 ECMAScript 2015。ES6 中引入的一些重要特性包括箭头函数、let 和 const 关键字、类、res 参数等。本章将讨论 ES6 版本中所有新增的特性。
ES6 新增特性
以下是 JavaScript ES6 版本中新增的方法、特性等。
- Arrow Functions
- Array find()
- Array findIndex()
- Array from()
- Array keys()
- Classes
- const keyword
- Default Parameters
- For/of
- Function Rest Parameter
- JavaScript Modules
- let keyword
- Map Objects
- New Global Methods
- New Math Methods
- New Number Methods
- New Number Properties
- Promises
- Set Objects
- String.endsWith()
- String.includes()
- String.startsWith()
- Symbol
- 扩展运算符
我们已通过示例详细解释了每个特性。
JavaScript 箭头函数
箭头函数是一种编写更短函数代码的方法。箭头函数的概念允许您在定义函数时无需使用 function 关键字、花括号和 return 关键字。
示例
在下面的代码中,func() 是一个常规函数,变量 subtracts 存储的是箭头函数的值。
<html>
<body>
<div id = "output">20 加 10 的减法是: </div>
<script>
/* Normal function
function func(a, b) {
return a - b;
}
*/
// Arrow function
const subtract = (a, b) => a - b;
document.getElementById("output").innerHTML += subtract(20, 10);
</script>
</body>
</html>
输出
20 加 10 的减法是: 10
JavaScript 数组 find() 方法
JavaScript array.find() 方法返回符合特定条件的第一个元素。
示例
在下面的代码中,我们使用 array.find() 方法查找第一个长度小于 4 的数组元素。
<html>
<body>
<div id = "output">第一个长度小于 4 的数组元素是: </div>
<script>
const strs = ["Hello", "World", "How", "are", "You"];
function func_len(value, index, array) {
return value.length < 4;
}
document.getElementById("output").innerHTML += strs.find(func_len);
</script>
</body>
</html>
输出
第一个长度小于 4 的数组元素是: How
JavaScript 数组 findIndex()
JavaScript array.findIndex() 方法与 array.find() 方法类似,但它返回符合特定条件的第一个元素的索引。它返回从 0 开始的索引。
示例
在下面的代码中,我们使用 array.findIndex() 方法查找第一个长度小于 4 的元素的索引。
<html>
<body>
<div id = "output">第一个长度小于 4 的数组元素是: </div>
<script>
const strs = ["Hello", "World", "How", "are", "You"];
function func_len(value, index, array) {
return value.length < 4;
}
document.getElementById("output").innerHTML += strs.findIndex(func_len);
</script>
</body>
</html>
输出
第一个长度小于 4 的数组元素是: 2
JavaScript Array from()
JavaScript Array.from() 方法通过传入的可迭代对象创建一个数组。
示例
在下面的代码中,我们使用 Array.from() 方法通过字符串创建一个数组。当然,您也可以将可迭代对象作为 Array.from() 方法的参数传入。
<html>
<body>
<div id = "output">Hello 字符串的数组是: </div>
<script>
document.getElementById("output").innerHTML += Array.from("Hello");
</script>
</body>
</html>
输出
Hello 字符串的数组是: H,e,l,l,o
JavaScript 数组 keys()
JavaScript array.keys() 方法返回一个迭代器来迭代数组中的键。数组元素的键是数组元素的索引。
示例
在下面的代码中,我们使用 keys() 方法获取 nums[] 数组中键的迭代器。之后,我们使用 for/of 循环遍历数组中的键。
<html>
<body>
<div id = "demo">nums 数组的键是: <br></div>
<script>
const output = document.getElementById("demo");
const nums = [45, 67, 89, 342, 123, 12];
const iteratorNums = nums.keys();
for (let key of iteratorNums) {
output.innerHTML += key + "<br>";
}
</script>
</body>
</html>
输出
nums 数组的键是: 0 1 2 3 4 5
JavaScript 类
类在面向对象编程语言中至关重要。它是对象的蓝图。
您可以使用 class 关键字来定义类。您可以向类主体添加构造函数、属性和方法。要访问类的属性和方法,可以使用类实例。
示例
在下面的代码中,我们定义了动物类。
构造函数初始化了 name 和 isVegetarian 属性的值。getInfo() 方法返回动物信息。
我们创建了动物类的对象,并使用它来调用该类的 getInfo() 方法。
<html>
<body>
<div id = "output">The animal information is: </div>
<script>
class animal {
constructor(name, isVegetarian) {
this.name = name;
this.isVegetarian = isVegetarian;
}
getInfo() {
return "Name : " + this.name + ", " + "isVegetarian? : " + this.isVegetarian;
}
}
const lion = new animal("Lion", false);
document.getElementById("output").innerHTML += lion.getInfo();
</script>
</body>
</html>
输出
The animal information is: Name : Lion, isVegetarian? : false
JavaScript const 关键字
JavaScript const 关键字用于声明常量变量。声明常量变量时,需要对其进行初始化。
示例
在下面的代码中,"fruit"是一个常量变量。您无法重新初始化它的值。
<html>
<body>
<div id = "output">The value of the fruit variable is: </div>
<script>
const fruit = "Apple";
// fruit = "Banana"; This is Invalid
document.getElementById("output").innerHTML += fruit;
</script>
</body>
</html>
输出
The value of the fruit variable is: Apple
JavaScript let 关键字
JavaScript let 关键字用于定义块级作用域变量。
示例
在下面的代码中,我们在"if"块中使用 let 关键字定义了变量"a"。由于其作用域行为,它无法在"if"块外部访问。
<html>
<body>
<div id = "output"> </div>
<script>
if (true) {
let a = 20;
document.getElementById("output").innerHTML += "The value of a is: " + a;
}
// 您无法在这里访问它。
</script>
</body>
</html>
输出
The value of a is: 20
JavaScript 默认参数
默认参数意味着函数参数可以具有默认值。当您没有向函数传递足够的参数时,它会使用默认参数值。
示例
在下面的代码中,division() 函数接受两个参数。a 的默认值为 10,b 的默认值为 2。
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById("demo");
function division(a = 10, b = 2) {
return a / b;
}
output.innerHTML += "division(40, 5) => " + division(40, 5) + "<br>";
output.innerHTML += "division(40) => " + division(40) + "<br>";
output.innerHTML += "division() => " + division();
</script>
</body>
</html>
输出
division(40, 5) => 8 division(40) => 20 division() => 5
JavaScript forof 循环
JavaScript forof 循环可以像遍历数组、字符串、集合、映射等一样遍历可迭代对象。
示例
在下面的代码中,我们遍历数字数组,并在输出中打印数组中的每个元素。
<html>
<body>
<div id = "output">数组元素为: </div>
<script>
const array = [10, 67, 82, 75, 80];
for (let number of array) {
document.getElementById("output").innerHTML += number + ", ";
}
</script>
</body>
</html>
输出
数组元素为: 10, 67, 82, 75, 80,
JavaScript 函数剩余参数
如果您不确定函数参数的数量,可以使用剩余参数。剩余参数允许您将多个参数收集到一个数组中。
示例
我们将以下代码与 sum() 函数一起使用剩余参数。剩余参数的名称可以是有效的标识符,并与扩展 () 运算符一起使用。
sum() 函数将多个数值相加并返回它们。
<html>
<body>
<div id = "output">sum(10, 67, 82, 75, 80) = </div>
<script>
function sum(...restParam) {
let res = 0;
for (let ele of restParam) {
res += ele;
}
return res;
}
document.getElementById("output").innerHTML += sum(10, 67, 82, 75, 80);
</script>
</body>
</html>
输出
sum(10, 67, 82, 75, 80) = 314
JavaScript 模块
在 JavaScript 中,您可以创建不同的模块来编写可重用的代码。之后,您可以将这些模块导入到不同的 JavaScript 文件中。
默认导出/导入模块
const moduleMath = "This is the default value."; export default moduleMath; // 导出模块
在其他 JavaScript 文件中
// 导入默认模块 import moduleMath from './filename.js'; console.log(moduleMath);
命名导出/导入模块
您还可以从模块中导出特定的函数或属性,并将其导入到其他 JavaScript 文件中。
// 导出变量
export const size = 90;
// 导出函数
export function add(a, b) {
return a + b;
}
在其他 JavaScript 文件中
// 导入特定属性和函数
import { size, add} from './filename.js';
console.log(myVariable); // 90
console.log(add(15, 25)); // 40
JavaScript Map 对象
Map 用于存储键值对。您可以使用 Map() 构造函数来定义 Map。
示例
在下面的示例中,我们使用 Map 来存储水果的名称和价格。set() 方法用于将键值对插入到水果 Map 中,get() 方法用于从 Map 中获取特定键的值。
<html>
<body>
<div id = "output1">The price of the Apple is: </div>
<div id = "output2">The price of the Banana is: </div>
<script>
const fruit = new Map();
fruit.set("Apple", 50);
fruit.set("Banana", 60);
document.getElementById("output1").innerHTML += fruit.get("Apple") + "<br>";
document.getElementById("output2").innerHTML += fruit.get("Banana");
</script>
</body>
</html>
输出
The price of the Apple is: 50 The price of the Banana is: 60
新的全局方法
ES6 新增了以下两个全局方法。
- isFinite()
- isNaN()
isFinite()
isFinite() 方法检查作为参数传递的值是否为有限值。
示例
在下面的代码中,num1 变量包含无穷大值,num2 变量包含有效数值。
我们使用 isFinite() 方法检查 num1 和 num2 变量的值是否为有限值。
<html>
<body>
<div id = "output"> </div>
<script>
const num1 = 6453 / 0;
const num2 = 90;
document.getElementById("output").innerHTML =
"isFinite(6453 / 0): " + isFinite(num1) + "<br>" +
"isFinite(90): " + isFinite(num2);
</script>
</body>
</html>
输出
isFinite(6453 / 0): false isFinite(90): true
isNaN()
isNaN() 方法检查参数是否为有效数字。如果是数字值,则返回 false。
示例
在下面的代码中,isNaN() 方法对 num1 变量返回 true,因为它包含字符串,而该字符串不是数字。对于 num2 变量,isNaN() 方法返回 false,因为它包含数字值。
<html>
<body>
<div id = "output"> </div>
<script>
const num1 = "Hello";
const num2 = 867;
document.getElementById("output").innerHTML =
"isNaN(num1): " + isNaN(num1) + "<br>" +
"isNaN(num2): " + isNaN(num2);
</script>
</body>
</html>
输出
isNaN(num1): true isNaN(num2): false
新的 JavaScript 数学方法
在 ES6 中,Math 对象添加了 5 个新方法。
- Math.cbrt() − 用于求给定数字的立方根。
- Math.log2() 用于求数字的对数,并以 2 为底。
- Math.log10() 用于求数值的以 10 为底的对数。
- Math.trunc() 用于从浮点数中删除小数部分并将其转换为整数。
- Math.sign() 根据作为参数传递的数字的符号返回 1、0 或 -1。
示例:Math.cbrt()
以下代码求 64 的立方根。
<html>
<body>
<div id = "output">The cube root of the 64 is: </div>
<script>
document.getElementById("output").innerHTML += Math.cbrt(64);
</script>
</body>
</html>
示例:Math.log2()
以下代码求 30 以 2 为底的对数。
<html>
<body>
<div id = "output">The value of logarithm of 30 base 2 is: </div>
<script>
document.getElementById("output").innerHTML += Math.log2(30);
</script>
</body>
</html>
示例:Math.log10()
以下代码求以 10 为底的 10 的对数。
<html>
<body>
<div id = "output">The value of the logarithm of 10 base 10 is: </div>
<script>
document.getElementById("output").innerHTML += Math.log10(10);
</script>
</body>
</html>
示例:Math.trunc()
以下代码使用 Math.trunc() 方法截断浮点数。
<html>
<body>
<div id = "output">After converting 23.2 to integer is: </div>
<script>
document.getElementById("output").innerHTML += Math.trunc(23.2);
</script>
</body>
</html>
示例: Math.sign()
<html>
<body>
<div id="output1">Math.sign(23): </div>
<div id="output2">Math.sign(-23): </div>
<script>
document.getElementById("output1").innerHTML += Math.sign(23);
document.getElementById("output2").innerHTML += Math.sign(-23);
</script>
</body>
</html>
新的数字方法
ES6 中新增了两个数字方法。
Number.isInteger() − 检查作为参数传递的数字是整数还是整型数。
Number.isSafeInteger() − 检查该数字是否可以表示为 64 位双精度数。
示例
以下代码检查 10 和 10.5 是否为整数值。此外,它使用 number 类的 isSafeInteger() 方法来检查该数字是否为安全整数。
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById("demo");
output.innerHTML += "Is 10 integer? " + Number.isInteger(10) + "<br>";
output.innerHTML += "Is 10.5 integer? " + Number.isInteger(10.5) + "<br>";
output.innerHTML += "Is 10000 safe integer? " + Number.isSafeInteger(10000) + "<br>";
output.innerHTML += "Is 10000000000000000000000 safe integer? " + Number.isSafeInteger(10000000000000000000000);
</script>
</body>
</html>
输出
Is 10 integer? true Is 10.5 integer? false Is 10000 safe integer? - true Is 10000000000000000000000 safe integer? - false
新的数字属性
ES6 中新增了三个数字属性。
EPSILON − 返回 Epsilon 的值。
MIN_SAFE_INTEGER − 返回 64 位数字可以表示的最小整数值。
MAX_SAFE_INTEGER − 返回 64 位数字可以表示的最大数字。
示例
以下代码展示了 JavaScript 中 Epsilon 常量的值、安全整数的最小值和安全整数的最大值。
<html>
<body>
<div id = "output1">The value of Epsilon is: </div>
<div id = "output2">The minimum safe integer is: </div>
<div id = "output3">The maximum safe integer is: </div>
<script>
document.getElementById("output1").innerHTML += Number.EPSILON;
document.getElementById("output2").innerHTML += Number.MIN_SAFE_INTEGER;
document.getElementById("output3").innerHTML += Number.MAX_SAFE_INTEGER
</script>
</body>
</html>
输出
The value of Epsilon is: 2.220446049250313e-16 The minimum safe integer is: -9007199254740991 The maximum safe integer is: 9007199254740991
JavaScript Promise
在 JavaScript 中,Promise 用于异步处理代码。
它生成并消费代码。
示例
在下面的代码中,我们使用 Promise() 构造函数创建了一个 Promise。我们根据 Math 块的 random() 方法生成的随机值来解析和拒绝该 Promise。
之后,我们使用 then() 和 catch() 块来处理该 Promise。
<html>
<body>
<div id = "output"> </div>
<script>
// Creating a Promise
const newPromise = new Promise((res, rej) => {
setTimeout(() => {
const rand_value = Math.random();
if (rand_value < 0.5) {
res("Value is less than 0.5"); // Resolving the promise
} else {
rej("Value is greater than 0.5"); // Rejecting the promise
}
}, 1000); // Adding 1 second delay
});
// Consuming the Promise
newPromise
.then((res) => {
document.getElementById("output").innerHTML += res;
})
.catch((rej) => {
document.getElementById("output").innerHTML += rej;
});
</script>
</body>
</html>
输出
Value is greater than 0.5
JavaScript Set 集合对象
Set() 构造函数用于创建集合。该集合仅存储不同类型的唯一元素。
示例
在下面的代码中,我们创建了一个新集合,并将包含数字的数组作为 Set() 构造函数的参数传递。该集合仅包含唯一元素,您可以在输出中看到。
<html>
<body>
<div id = "output">The set elements are: </div>
<script>
const num_set = new Set([10, 20, 20, 42, 12]);
for (let num of num_set) {
document.getElementById("output").innerHTML += ", " + num;
}
</script>
</body>
</html>
输出
The set elements are: , 10, 20, 42, 12
JavaScript 新的字符串方法
ES6 中新增了三个字符串方法。
- endsWith() − 检查字符串是否以特定子字符串结尾。
- includes() − 检查字符串是否在任何位置包含该子字符串。
- startsWith() − 检查字符串是否以特定子字符串开头。
示例
以下示例通过"你好吗?我很好!"语句演示了如何使用 String 的 endsWith()、includes() 和 startsWith() 方法。
<html>
<body>
<div id = "output1">Does string end with 'fine'? </div>
<div id = "output2">Does string include 'are'? </div>
<div id = "output3">Does string start with 'How'? </div>
<script>
let str = "How are you? I'm fine!";
document.getElementById("output1").innerHTML += str.endsWith("fine!");
document.getElementById("output2").innerHTML += str.includes("are");
document.getElementById("output3").innerHTML += str.startsWith("How");
</script>
</body>
</html>
输出
Does string end with 'fine'? true Does string include 'are'? true Does string start with 'How'? true
JavaScript 符号
JavaScript 符号是 JavaScript 中的主要数据类型。在 JavaScript 中,每个符号都是唯一的。您可以使用它来创建唯一的 ID。
示例
在下面的代码中,我们定义了两个符号,并将相同的值作为参数传递。尽管如此,这两个符号仍然是唯一的,您可以在输出中看到这一点。
<html>
<body>
<div id = "output"> </div>
<script>
const sym1 = Symbol("a");
const sym2 = Symbol("a");
if (sym1 == sym2) {
document.getElementById("output").innerHTML += "sym1 and sym2 are equal. <br>";
} else {
document.getElementById("output").innerHTML += "sym1 and sym2 are not equal.";
}
</script>
</body>
</html>
输出
sym1 and sym2 are not equal.
JabaScript 扩展运算符
JavaScript 扩展运算符允许您创建可迭代对象的副本,例如数组、字符串等。
示例
以下代码演示了如何使用扩展运算符从字符串创建字符数组。
<html>
<body>
<div id = "output">The char array is: </div>
<script>
let str = "Hello World!";
const char = [...str];
document.getElementById("output").innerHTML += char;
</script>
</body>
</html>
输出
The char array is: H,e,l,l,o, ,W,o,r,l,d,!

