Array.isArray(监测该对象是否为数组)
用法:Array.isArray(arr)
返回值:Boolean
var arr = [],obj = {};
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false
filter(返回新数组,不会改变原数组,不会对空数组进行检测,只能做筛选,此方法会遍历完数组)
用法:Array.filter
var arr = [1,2,3,4];
var newArr = arr.filter( (item, index) => {
return item % 2;
});
console.log(newArr); // [1,3];
find(返回新数组,不会改变原数组,不会对空数组进行检测,只能做筛选,此方法满足条件立即跳出)
var arr = [1,2,3,4];
var newArr = arr.filter( (item, index) => {
return item === 1;
});
console.log(newArr); // [1];
reduce、reduceRight(对数组中的每个元素(从左到右或从右到左)执行callback函数累加,将其减少为单个值。)
元素相加
var arr = [1,2,3,4];
var newArr = arr.reduce((sum, value) => {
return sum + value;
},0);
console.log(newArr); // 10
合并数组
const concatArr = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => {
return a.concat(b);
}, []); // [0, 1, 2, 3, 4, 5]
数组去重
var obj = {};
let personList = [
{id: 0, name: "小明"},
{id: 1, name: "小红"},
{id: 2, name: "小白"},
{id: 3, name: "小白"},
{id: 1, name: "小明"},
{id: 2, name: "小红"},
];
personList = personList.reduce((cur,next) => {
obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
return cur;
},[]);
console.log(personList);
map (返回新数组,不会改变原数组,可以在原有数据基础上做运算)
var arr = [1,2,3,4];
var newArr = arr.map( (item, index) => {
return item + 1;
});
console.log(newArr); // [2,3,4,5];
Array.every(检测数组中的每一个元素是否都通过了callback测试,全部通过返回true,否则返回false。)
var arr = [1,2,3,4];
var arr1 = [1,2,3,"4"];
var newArr = arr.every((item) => {
return typeof item === "number";
});
var newArr1 = arr1.every((item) => {
return typeof item === "number";
});
console.log(newArr); // true
console.log(newArr1); // false