JavaScript 中的数组方法和字符串方法有很大的区别。数组方法是用于操作数组的,而字符串方法是用于操作字符串的。
数组方法可以添加、删除、替换、排序、搜索、迭代、过滤和映射数组元素。以下是一些常见的数组方法示例:
const numbers = [1, 2, 3, 4, 5];
// 添加元素
numbers.push(6);
// 删除元素
numbers.splice(2, 1);
// 替换元素
numbers[1] = 10;
// 排序元素
numbers.sort((a, b) => a - b);
// 搜索元素
const index = numbers.indexOf(4);
// 迭代元素
numbers.forEach(num => console.log(num));
// 过滤元素
const filteredNumbers = numbers.filter(num => num > 3);
// 映射元素
const mappedNumbers = numbers.map(num => num * 2);
字符串方法可以修改、搜索、替换、分割、连接、截断和转换字符串。以下是一些常见的字符串方法示例:
const str = "Hello, World!";
// 修改字符串
const newStr = str.toUpperCase();
// 搜索字符串
const index = str.indexOf("World");
// 替换字符串
const replacedStr = str.replace("Hello", "Hi");
// 分割字符串
const arr = str.split(",");
// 连接字符串
const newStr = arr.join(" ");
// 截断字符串
const truncatedStr = str.slice(0, 5);
// 转换字符串
const num = parseInt("123");
总体而言,数组方法和字符串方法具有不同的功能和用途,需要根据具体的需求来选择使用。