JavaScript字符串类函数
JavaScript字符串类提供了许多常用的函数以便我们快速地处理字符串,以下是前端常用的字符串类函数以及相应的示例:
语法:string.substring(start, end)
参数:
start: 必须。一个非负整数,规定要提取的子串的第一个字符的位置。
end: 可选。一个非负整数,比要提取的子串的最后一个字符的位置多1。如果省略该参数,那么返回从 start 到最后的全部字符。
返回值:一个新字符串,包含从 start 到 end (不包括 end)之间的所有字符,或从 start 到字符串末尾的全部字符(如果忽略了 end 参数)。
示例代码:
const str = "hello world";
console.log(str.substring(1, 4)); // "ell"
console.log(str.substring(6)); // "world"
split()
功能:根据指定的分隔符将一个字符串分割为多个子字符串,并将结果存储到数组中。
语法:string.split(separator, limit)
参数:
separator: 必须。字符串或正则表达式,表示为要在字符串中进行分割的字符或模式。
limit: 可选。限定返回的子串数量。
返回值:一个新数组,包含指定字符串中的各个子串,以分隔符指定的位置断开。
示例代码:
const str = "apple,banana,orange";
console.log(str.split(",")); // ["apple", "banana", "orange"]
replace()
功能:在字符串中找到指定的子字符串或模式,并用另一个字符串或函数替换它。
语法:string.replace(searchValue, replaceValue)
参数:
searchValue: 必须。字符串或正则表达式,表示为要在 string 中进行查找的文本或模式。
replaceValue: 必须。一个字符串或函数,规定了替换文本或生成替换文本的函数。
返回值:一个新字符串,其中所有被替换文本的出现位置都被替换为替换文本。
示例代码:
const str = "hello world";
console.log(str.replace("world", "universe")); // "hello universe"
slice()
功能:从字符串中提取一个新的字符串,其中包含从指定的开始位置到结束位置的所有字符。
语法:string.slice(start, end)
参数:
start: 必须。一个非负整数,规定要提取的子串的第一个字符的位置。
end: 可选。一个非负整数,比要提取的子串的最后一个字符的位置多1。如果省略该参数,那么返回从 start 到最后的全部字符。
返回值:一个新字符串,包含从 start 到 end (不包括 end)之间的所有字符。
示例代码:
const str = "hello world";
console.log(str.slice(6)); // "world"
toLowerCase()
功能:将一个字符串转换为小写字母。
语法:string.toLowerCase()
参数:无。
返回值:一个新字符串,其中所有大写字母被转换为小写字母。
示例代码:
const str = "HELLO WORLD";
console.log(str.toLowerCase()); // "hello world"
toUpperCase()
功能:将一个字符串转换为大写字母。
语法:string.toUpperCase()
参数:无。
返回值:一个新字符串,其中所有小写字母被转换为大写字母。
示例代码:
const str = "hello world";
console.log(str.toUpperCase()); // "HELLO WORLD"
数组类
forEach
遍历数组并对每个元素执行一次回调函数。
const arr = [1, 2, 3];
arr.forEach((item) => console.log(item)); // 1 2 3
map
遍历数组并对每个元素执行一次回调函数,将回调函数的返回值组成一个新数组返回。
const arr = [1, 2, 3];
const newArr = arr.map((item) => item * 2);
console.log(newArr); // [2, 4, 6]
reduce
遍历数组并对每个元素执行一次回调函数,将回调函数的返回值和之前的累计值作为下次回调的参数,最后返回累计值。
const arr = [1, 2, 3];
const sum = arr.reduce((prev, curr) => prev + curr, 0);
console.log(sum); // 6
filter
遍历数组并对每个元素执行一次回调函数,如果回调函数返回true,将该元素加入新数组并返回。
const arr = [1, 2, 3];
const newArr = arr.filter((item) => item > 1);
console.log(newArr); // [2, 3]
数学类
Math.round
将一个数四舍五入到最接近的整数。
console.log(Math.round(2.4)); // 2
console.log(Math.round(2.6)); // 3
Math.random
返回0-1之间的随机数。
console.log(Math.random()); // 0.xxx
Math.max
返回一组数中的最大值。
console.log(Math.max(1, 2, 3)); // 3
Math.min
返回一组数中的最小值。
console.log(Math.min(1, 2, 3)); // 1
对象类
Object.keys
返回对象所有可枚举属性的键名组成的数组。
const obj = { name: "Tom", age: 18 };
console.log(Object.keys(obj)); // ["name", "age"]
Object.assign
将多个源对象合并到目标对象上。
const obj1 = { name: "Tom" };
const obj2 = { age: 18 };
const newObj = Object.assign(obj1, obj2);
console.log(newObj); // { name: "Tom", age: 18 }