<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
/*
数组方法
1、forEatch 遍历修改原数组
2、filter 过滤符合条件的数据,返回符合条件数据的数组
3、some 判断数组中是否有符合条件的数据,返回判断结果为布尔值
4、every 判断数组中是否全部符合条件,返回判断结果为布尔值
5、find 找到符合条件的第一个
6、findIndex 找到第一个符合条件的下标,未找到返回-1
*/
let potatos = [{
id: '1001',
weight: 50
}, {
id: '1002',
weight: 80
}, {
id: '1003',
weight: 120
}, {
id: '1004',
weight: 40
}, {
id: '1005',
weight: 110
}, {
id: '1006',
weight: 60
}]
let w = [50, 80, 120, 40, 110, 60]
// 1、农民:我要催熟(批量增重) forEach 注:没有返回值,直接改变原数组
potatos.forEach(item => {
item.weight += 20
});
console.log(potatos);
/* [{
id: '1001',
weight: 70
}, {
id: '1002',
weight: 100
}, {
id: '1003',
weight: 140
}, {
id: '1004',
weight: 60
}, {
id: '1005',
weight: 130
}, {
id: '1006',
weight: 80
}] */
// 2、老板:我只要大土豆(筛选过滤:filter)注:不会改变原数组,返回符合条件数组
let bigPotatos = potatos.filter(item => item.weight >= 100) // 重量大于等于100
console.log(bigPotatos);
// 3、有没有大土豆(some判断)注:返回判断结果,布尔值
let isBig = potatos.some(item => item.weight >= 100)
console.log(isBig); // true
// 4、老板:难道全都是大的吗(全符合:every)注: every`对每一个元素执行一个`callback`,直到它找到一个使 `callback` 返回 `false`的元素(没那么大的土豆),就返回`false`,直到遍历完成也没有返回`false`的话,就返回`true
let isAllBig = potatos.every(item => item.weight >= 100)
console.log(isAllBig); // false
// 5、顾客:给我个大土豆(返回一个符合的:find)
let big = potatos.find(item => item.weight >= 100)
console.log(big);// { id: '1002', weight: 100}
// 6、收银员:这是第几个(findIndex)
let bigIndex = potatos.findIndex(item => item.weight >= 100)
console.log(bigIndex); // 1
// 7、老板:今年收成如何呀(递归累加:reduce)
let allWeight = w.reduce((sum, w) => sum + w, 0)
console.log(allWeight);
</script>
</html>
数组方法总结
最新推荐文章于 2022-07-25 13:55:18 发布