数组方法
修改原数组
push(),pop(),shift(),unshift(),reserve(),sort(),splice(),fill(),copyWithin()
不修改原数组
map(),有或无返回值
forEach(), 无返回值
filter(potato=>{return potato.weight>100} ),挑选大土豆 // [{id:‘103’,weight:120},{id:‘133’,weight:110}]
every(potato=>{return potato.weight>100}), 全是大土豆吗? //false
some(potato=>{return potato.weight>100}),有大土豆吗?//true
reduce((sum,p)=>{return p.weight+sum},0),今年收成 //460
find(potato=>{return potato.weight>100}),挑第一个大土豆// {id:‘103’.weight:120}
findIndex(potato=>{return potato.weight>100}) 这是第几(索引)个土豆 //2
flat(),
concat(),连接数组
join(),返回转换后的字符串
slice()截取数组为主,也可以截取字符串【a,b)//截数组返回数组,字符串返回字符串
at(-1) 返回数组最后一位
Array.of()将一组值转化为数组,返回一个新数组,并且不考虑参数的数量或类型。
Math.max.apply(null,arr) 数组中最大值
let arr=[1,2,3,4,5]
// keys()
for (let index of arr.keys()) {
console.log(index); // 一次返回 0 1 2 3 4
}
// values()
for (let index of arr.values()) {
console.log(index); // 一次返回 1 2 3 4 5
}
// entries()
for (let index of arr.entries()) {
console.log(index); // 一次返回 [0, 1] [1, 2] [2, 3] [3, 4] [4, 5]
}
//数组转对象
let arr = [
["a", 1],
["b", 2],
]
let obj = Object.fromEntries(arr);
console.log(obj); // {a: 1, b: 2}
注意
map
map有返回值会生成一个新数组,但不改变原数组,所以console.log(arr)还是[1,2,3,4]
let arr = [1, 2, 3, 4];
arr.map((item) => {
return item * item;
});
console.log(arr);//[1,2,3,4]
function square(arr) {
return arr.map(function (item) {
return item * item;
});
}
console.log(square(arr));//[1,4,9,16]
Set
//使用 Set 存储数据时,查找操作的时间复杂度为 O(1),比数组的 O(n) 要快得多
const dataSet = new Set([1, 2, 3, 4, 5]);
if (dataSet.has(3)) {
console.log('数据已经存在');
} else {
console.log('数据不存在');
}
Map
const arr = [1, 2, 3, 1, 2, 4, 5];
const countMap = new Map();
arr.forEach(item => {
countMap.set(item, (countMap.get(item) || 0) + 1);
});
console.log(countMap.get(1)); // 2
console.log(countMap.get(2)); // 2