forEach(),map(),filter(),some(),every(),findIndex()
// forEach()没有返回值
var a = [1,2,3,4]
a.forEach(function(value,index,array){
console.log(value);
console.log(index);
console.log(array);
})
// map()有返回值,可以return 出来。
var a = [1,2,3,4];
var b = a.map(function (item,index,array) {
return item*10;
})
console.log(b);//-->[10, 20, 30, 40];
console.log(a);//-->[1, 2, 3, 4];
//filter()筛选遍历,返回的是一个新数组
var a = [1,2,3,4]
var b = a.filter(function(value,index,array){
return value>1
})
console.log(b)//[2,3,4]
//every()检测所有元素是否符合条件
var a = [1,2,3,4]
var b = a.every(function(value,index,array){
return value>1
})
console.log(b)//false
//some()返回是否存在,适合查找唯一的元素
var a = [1,2,3,4]
var b = a.some(function(value,index,array){
return value>1
})
console.log(b)//true
//findIndex() 方法返回符合条件的数组第一个元素位置
var a = [1,2,3,4]
var b = a.findIndex(function(value,index,array){
return value>1
})
console.log(b)//1
// reduce
//数组求和,求乘积
var arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
console.log( sum ); //求和,10
console.log( mul ); //求乘积,24
// 计算数组中每个元素出现的次数
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
let nameNum = names.reduce((pre,cur)=>{
if(cur in pre){
pre[cur]++
}else{
pre[cur] = 1
}
return pre
},{})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}
//数组去重
let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
if(!pre.includes(cur)){
return pre.concat(cur)
}else{
return pre
}
},[])
console.log(newArr);// [1, 2, 3, 4]
//将二维数组转化为一维
let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]
//将多维数组转化为一维
let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr = function(arr){
return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr(cur):cur),[])
}
console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]
//对象里的属性求和
var result = [
{
subject: 'math',
score: 10
},
{
subject: 'chinese',
score: 20
},
{
subject: 'english',
score: 30
}
];
var sum = result.reduce(function(prev, cur) {
return cur.score + prev;
}, 0);
console.log(sum) //60
for...of异步遍历
function muti(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num * num)
}, 1000);
});
}
const nums = [1, 2, 3];
// forEach遍历,没有延迟,直接全部输出打印
nums.forEach(async (i) => {
const result = await muti(i)
console.log(result);
});
// for of异步遍历,有1000毫秒延迟输出
(async function () {
for (const i of nums) {
const result = await muti(i)
console.log(result);
}
})()
// 1
// 4
// 9