返回
ES6 数值、字符串、函数、数组扩展用法详解
前端
2023-09-10 09:35:44
ES6 字符串扩展
includes() 方法
includes()
方法用于判断字符串是否包含指定的子字符串。如果包含,则返回 true
;否则,返回 false
。
const str = 'Hello World';
console.log(str.includes('World')); // true
console.log(str.includes('Universe')); // false
startsWith() 方法
startsWith()
方法用于判断字符串是否以指定的子字符串开头。如果开头,则返回 true
;否则,返回 false
。
const str = 'Hello World';
console.log(str.startsWith('Hello')); // true
console.log(str.startsWith('World')); // false
endsWith() 方法
endsWith()
方法用于判断字符串是否以指定的子字符串结尾。如果结尾,则返回 true
;否则,返回 false
。
const str = 'Hello World';
console.log(str.endsWith('World')); // true
console.log(str.endsWith('Hello')); // false
ES6 数值扩展
Number.isInteger() 方法
Number.isInteger()
方法用于判断一个数字是否为整数。如果数字是整数,则返回 true
;否则,返回 false
。
console.log(Number.isInteger(10)); // true
console.log(Number.isInteger(10.5)); // false
Number.isNaN() 方法
Number.isNaN()
方法用于判断一个值是否为 NaN
(非数字)。如果值为 NaN
,则返回 true
;否则,返回 false
。
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(10)); // false
ES6 函数扩展
箭头函数
箭头函数是 ES6 中引入的一种简写函数语法。箭头函数没有自己的 this
,并且不能使用 arguments
对象。
const sum = (a, b) => a + b;
console.log(sum(1, 2)); // 3
剩余参数
剩余参数允许你将不定数量的参数传递给函数。剩余参数必须是函数的最后一个参数。
function sum(...numbers) {
return numbers.reduce((a, b) => a + b);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
ES6 数组扩展
Array.from() 方法
Array.from()
方法将类数组对象转换为真正的数组。
const arrayLike = {
0: 'Hello',
1: 'World',
length: 2
};
const array = Array.from(arrayLike);
console.log(array); // ['Hello', 'World']
Array.of() 方法
Array.of()
方法创建一个新的数组,其中包含一个或多个元素。
const array = Array.of(1, 2, 3, 4, 5);
console.log(array); // [1, 2, 3, 4, 5]
Array.find() 方法
Array.find()
方法返回数组中第一个满足给定测试函数的元素。
const array = [1, 2, 3, 4, 5];
const even = array.find(element => element % 2 === 0);
console.log(even); // 2
Array.findIndex() 方法
Array.findIndex()
方法返回数组中第一个满足给定测试函数的元素的索引。
const array = [1, 2, 3, 4, 5];
const evenIndex = array.findIndex(element => element % 2 === 0);
console.log(evenIndex); // 1
总结
ES6 中的这些扩展功能可以帮助你编写更简洁、更易读的代码。通过使用这些扩展功能,你可以提高代码的可维护性和可读性。