一,增、删、改(会改变原数组)
- push() - 在尾部添加一个元素
- pop() - 删除最尾部的元素
- unshift() - 在头部添加一个元素
- shift() - 删除头部的元素
- splice(index, howmany, item) - 实现数组的删除、增加、修改 [howmany为删除多少个]
删除:arr.splice(2, 5); // 即从索引2开始,删除5个元素
arr.splice(0); // 即从0开始,相当于清空数组
增加:arr.splice(2, 0, '张三') // 在索引2的位置,删除0个元素,添加一个元素'张三'
修改:arr.splice(2, 1, '李四'); // 原理即为替换,删除一个增加一个便实现修改
二,查询、拼接(不改变原数组)
- sclice(start, end) - 查询并返回索引start到end的部分(不包含end),返回新数组
如果start和end为负数,则从尾部算起;如果start和end为小数,则只取整数部分算起
- concat(arr2, arr3) - 实现数组的拼接(多个任意项),返回新数组
arr.concat() // 不传入任何数组参数可实现arr数组的复制
三,数组转换为字符串(不改变原数组)
- toString() - 转换成字符串并返回(以逗号分隔)
[1, 2, 3, 4].toString(); // "1,2,3,4"
- join(split) - 按照指定的分隔符,将数组转换成字符串并返回
[1, 2, 3, 4].join('-'); // "1-2-3-4"
四,检测数组是否包含某一项(不改变原数组)
- indexOf(item) - 查询当前项item在数组中第一次出现的位置,返回-1为不包含
- lastIndexOf(item) - 查询当前项item在数组中最后一次出现的位置,返回-1为不包含
- includes(item) - 查询数组中是否包含item项,返回true或false
- some(callback(item, index, array), [thisArg]) - 遍历数组并判断数组中只要有一项满足就返回true,都不成立返回false。可选参数thisArg是执行函数期间的this指向
- every(callback(item, index, array), [thisArg]) - 基本用法与some类似,不同的是every只要有一项不满足的就返回false,都满足才返回true。
五,查找、过滤数组满足条件的项(不改变原数组)
- find(callback(item, index, array), [thisArg]) - 循环数组,找到第一个满足条件的项并返回(没找到返回undefined)
[{name: '张三', age: 12}, {name: '李四', age: 24}].find(function(item){ item.name === '张三' })
- findIndex(callback(item, index, array), [thisArg]) - 与find方法一样,不同是查询的是索引
- filter(callback(item, index, array), [thisArg]) - 过滤数组,并(浅拷贝)返回数组的一部分
六,排序与排列(会改变原数组)
- sort([callback(a, b)]) - 将原数组按照大小排序,并返回排序后的数组。可以传递函数参数
函数中返回a-b为升序,返回b-a为降序
var arr = [11, 2, 32, 6];
arr.sort(function(a, b) {
return a - b; // 升序
})
console.log(arr); // 2,6,11,32
- reverse() - 逆转数组的顺序
七,遍历与映射(不改变原数组)
- forEach(callback(item, index)) - 遍历数组中的每一个元素,不返回
- map(callback(item, index)) - 遍历并映射数组,返回映射后的新数组
八,其他工具方法
- isArray() - 判断当前变量是否是数组
- Array.form(arrLike, [mapFun(item, index)], [thisArg]) - 将类数组或可迭代对象转换成浅拷贝的新数组。如果传入函数参数,则目标数组中的每个元素都会先传入函数处理,再将处理后的值返回到新数组中。
Array.from('245'); // ['2', '4', '5']
Array.from([2, 4, 5], function(item) {
return item + 1; // [3, 5, 6]
});
- Array.of([a], [b], [c], ...) - 将一个或一组值转换成数组
Array.of(1); // [1]
Array.of(1,'haha', true); // [1, 'haha', true]
Array.of(); // []
- fill(value, [start], [end]) - 用一个值填充数组,如果传入了参数start和end,就在指定位置填充
- reduce(callback(prevVal, currVal, index), [initValue]) - 遍历数组的并为每个值执行callback函数,callback的返回值作为下一次迭代的参数传入,以此类推。
callback的第1个参数prevVal:如果传入initValue初始值,则首次循环为初始值;否则,首次循环取数组的第一个值。
callback的第3个参数index:如果传入initValue初始值,则首次循环为0;否则,首次循环为1。
var arr = [1,2,3];
var initVal = 2;
const total = arr.reduce((prevVal, currentVal, index) => {
return prevVal + currentVal;
}, initVal);
console.log(total); // 8 ---- ((2 + 1) + 2) + 3
其他详细的方法,可以查看API:
MDNhttps://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array