返回
熟练掌握JavaScript数组常用方法,提升开发效率
见解分享
2023-09-20 03:11:41
JavaScript数组常用方法解析
一、实现数组增删改的方法
1.1 新增元素
在数组末尾新增元素,可以使用push()
方法:
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
在数组头部新增元素,可以使用unshift()
方法:
const arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
1.2 删除元素
从数组末尾删除元素,可以使用pop()
方法:
const arr = [1, 2, 3];
arr.pop();
console.log(arr); // [1, 2]
从数组头部删除元素,可以使用shift()
方法:
const arr = [1, 2, 3];
arr.shift();
console.log(arr); // [2, 3]
1.3 修改元素
修改数组中的某个元素,可以使用splice()
方法:
const arr = [1, 2, 3];
arr.splice(1, 1, 4);
console.log(arr); // [1, 4, 3]
第一个参数表示要修改元素的索引,第二个参数表示要删除的元素数量,第三个参数表示要新增的元素。
二、数组的查询和拼接
2.1 查询元素
查询数组中的某个元素,可以使用indexOf()
方法或lastIndexOf()
方法:
const arr = [1, 2, 3, 4, 5];
console.log(arr.indexOf(3)); // 2
console.log(arr.lastIndexOf(3)); // 2
indexOf()
方法返回首次出现的元素索引,lastIndexOf()
方法返回最后一次出现的元素索引。
2.2 拼接数组
拼接两个或多个数组,可以使用concat()
方法:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);
console.log(arr3); // [1, 2, 3, 4, 5, 6]
三、把数组转化为字符串
把数组转化为字符串,可以使用join()
方法:
const arr = [1, 2, 3];
const str = arr.join(',');
console.log(str); // "1,2,3"
第一个参数表示要使用的分隔符,默认为逗号。
四、检测数组中是否包含某一项
检测数组中是否包含某一项,可以使用includes()
方法:
const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
console.log(arr.includes(4)); // false
五、数组的排序或者排列
5.1 排序数组
排序数组,可以使用sort()
方法:
const arr = [1, 3, 2];
arr.sort();
console.log(arr); // [1, 2, 3]
sort()
方法默认按照升序排序,也可以传入一个比较函数来指定排序规则。
5.2 排列数组
排列数组,可以使用reverse()
方法:
const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]
六、遍历数组中的每一项
遍历数组中的每一项,可以使用forEach()
方法:
const arr = [1, 2, 3];
arr.forEach((item, index) => {
console.log(`第${index+1}项:${item}`);
});
或者使用for...of
循环:
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item);
}
掌握这些数组常用方法,可以帮助您在开发过程中更加高效地处理数组相关的问题。