揭秘 Es6 字符串、数字、数组之新增方法,带你飞向编程巅峰
2023-09-29 01:52:17
Es6字符串新增方法,让我们一起来看看这些新增方法都有哪些。
- 字符串查找遍历(for of)
ES6 中的字符串可以像数组一样使用 for of 循环进行遍历。这使得字符串的遍历更加方便,也让代码更加简洁。
const str = "Hello World!";
for (const char of str) {
console.log(char);
}
输出结果:
H
e
l
l
o
W
o
r
l
d
!
- search(可以解析正则)
ES6 中的字符串提供了 search() 方法,可以用来搜索字符串中的子字符串。search() 方法可以接收正则表达式作为参数,这使得字符串的搜索更加灵活。
const str = "Hello World!";
const result = str.search(/World/);
console.log(result); // 输出:6
- 唯一能解析正则的方法 math(字符串的方法,可以接收正则)
ES6 中的字符串提供了 match() 方法,可以用来匹配字符串中的子字符串。match() 方法可以接收正则表达式作为参数,这使得字符串的匹配更加灵活。
const str = "Hello World!";
const result = str.match(/World/);
console.log(result); // 输出:["World"]
- replace(字符串的方法,可以接收正则)
ES6 中的字符串提供了 replace() 方法,可以用来替换字符串中的子字符串。replace() 方法可以接收正则表达式作为参数,这使得字符串的替换更加灵活。
const str = "Hello World!";
const result = str.replace(/World/, "Universe");
console.log(result); // 输出:Hello Universe!
数字新增方法
- Math.sign()
ES6 中的 Math 对象提供了 sign() 方法,可以用来获取数字的符号。sign() 方法返回一个数字,如果是正数,则返回 1;如果是负数,则返回 -1;如果是 0,则返回 0。
console.log(Math.sign(1)); // 输出:1
console.log(Math.sign(-1)); // 输出:-1
console.log(Math.sign(0)); // 输出:0
- Math.trunc()
ES6 中的 Math 对象提供了 trunc() 方法,可以用来获取数字的整数部分。trunc() 方法返回一个数字,如果是正数,则返回小于或等于该数字的最大整数;如果是负数,则返回大于或等于该数字的最小整数。
console.log(Math.trunc(1.5)); // 输出:1
console.log(Math.trunc(-1.5)); // 输出:-1
console.log(Math.trunc(0.5)); // 输出:0
数组新增方法
- Array.from()
ES6 中的 Array 对象提供了 from() 方法,可以用来将其他类型的数据转换成数组。from() 方法可以接收字符串、对象、Set 等类型的数据作为参数,并返回一个由这些数据组成的数组。
const str = "Hello World!";
const arr = Array.from(str);
console.log(arr); // 输出:["H", "e", "l", "l", "o", "W", "o", "r", "l", "d", "!"]
- Array.find()
ES6 中的 Array 对象提供了 find() 方法,可以用来查找数组中第一个满足条件的元素。find() 方法接收一个回调函数作为参数,该回调函数返回一个布尔值。如果回调函数返回 true,则该元素就是第一个满足条件的元素。
const arr = [1, 2, 3, 4, 5];
const result = arr.find((element) => {
return element > 3;
});
console.log(result); // 输出:4
- Array.findIndex()
ES6 中的 Array 对象提供了 findIndex() 方法,可以用来查找数组中第一个满足条件的元素的索引。findIndex() 方法接收一个回调函数作为参数,该回调函数返回一个布尔值。如果回调函数返回 true,则该元素就是第一个满足条件的元素。
const arr = [1, 2, 3, 4, 5];
const result = arr.findIndex((element) => {
return element > 3;
});
console.log(result); // 输出:3
- Array.includes()
ES6 中的 Array 对象提供了 includes() 方法,可以用来判断数组中是否包含某个元素。includes() 方法接收一个元素作为参数,如果数组中包含该元素,则返回 true;否则,返回 false。
const arr = [1, 2, 3, 4, 5];
const result = arr.includes(3);
console.log(result); // 输出:true