一、数组遍历
-
for循环
优点:灵活性高,根据索引进行遍历,性能最佳
缺点:代码相对繁琐,需要手动管理索引
适用场景:追求极致性能,并且数组长度已知 -
forEach (item, index)
优点:语法简洁易读,无需手动管理索引,不会遍历原型链
缺点:无法使用break、continue跳出循环,除非抛出异常
适用场景:需要简洁语法遍历数组索引和元素,并不需要中途跳出循环 -
for…of (item)
优点:语法简洁,可直接获取数组元素,可以遍历任何可迭代对象,不会遍历原型链
缺点:无法获取当前元素的索引
适用场景:需要简洁语法遍历数组元素,并且不需要索引,set、map、generator -
map
优点:可以同时遍历和转换数组的元素,返回一个新数组
缺点:不适合仅需要遍历不需要返回新数组的情况
适用场景:需要根据原数组创建新数组,并对每个元素进行操作 -
for…in (index)
优点:可以遍历数组的索引(键)
缺点:会遍历原型链上的索引,可能导致意外结果,不推荐用于数组遍历
二、判断是否数组
-
Array.isArray()
最可靠 -
instanceof操作符
检测对象是否是某个构造函数的实例 -
constructor
返回对象的构造函数
若数组对象原型链被修改,则失效 -
Object.prototype.toString.call()
获取更具体的对象类型信息,数组返回’[object Array]’ -
Array构造函数的静态方法
Array.prototype
三、数组随机排序
arr.sort(() -> Math.random() - 0.5)
四、数组去重
- Array.from(new Set(arr))
- arr.forEach(item => {
if(indexOf)
}) - map.has和map.set
- for循环
Array.prototype.uniq = function() {
return this.filter((v, idx) => {
return this.indexOf(v, 0) === idx;
})
}
or
[...new Set(arr)]
五、类数组转换为数组
- Array.from(args)
- […args]
- [].slice.call(args)
- Array.protoype.slice.call(args)
六、其他
-
reduce((prev,cur,index,arr)=>{},initialValue)
返回回调函数执行后的一个值,如求和、求积 -
reduceRight: 与reduce相似,从右向左
-
slice、concat、…
无参数时,复制原数组。一维数组深拷贝,多维数组浅拷贝splice()截取数组
splice(开始索引,多少个)
splice(开始索引,多少个,要插入的数据) -
指定范围内的随机数
(min, max): Math.round(Math.random() * (max - min - 2) + min + 1)
[min, max]: Math.round(Math.round() * (max - min) + min)
(min, max]: Math.ceil(Math.round() * (max - min) + min)
- 其他API
Array.of() 将一组值转成数组
Array.fill()
Array.find()
Array.findIndex((value, index, arr){}) // 返回下标
entries() keys() values()
includes()
flat(n) 数组扁平化
flatMap() 只能展开一层数组