1.map
1.1 个人理解
- 映射 一个对一个 例如:[45,57,138]与[{name:'blue',level:0},{name:'zhangsan',level:99},{name:'lisi',level:100}] [45,67,99]与['不及格','不及格','及格']
1.2 代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>map数组</title>
<script>
let score = [12, 88, 59, 99];
// let result = score.map((item) => {
// if (item > 60) {
// return '及格'
// } else {
// return '不及格'
// }
// });
// 简写
let result = score.map(item => item > 60 ? '及格' : '不及格');
alert(score);
alert(result);
</script>
</head>
<body>
</body>
</html>
2.reduce
2.1 个人理解
- 汇总 一堆只出来一个 例如:算个总数[12,8,4]->24 算个平均数[12,8,4]->8
2.2 代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>reduce数组</title>
<script>
let score = [1, 3, 6, 9];
// 求和
let result = score.reduce((tmp, item, index) => {
// 前言://第一次时tmp,item,index分别为1,3,1,按此类推
console.log("第" + index + "次计算后返回结果:" + tmp);
// tmp:每次计算后返回结果,依次为1,3,6 没有10,10作为最终输出
console.log("当前的值" + item);
// item:当前的值,依次为3,6,9
console.log("当前值的下标" + index);
// index:当前值的下标,依次为1,2,3 从1开始,而非0
return tmp + item;
});
// 两次效果相同
// let result = score.reduce((tmp, item) => {
// return tmp + item;
// });
alert(result);
// 算平均数
let scoreone = [1, 3, 6, 14];
let resultone = scoreone.reduce((tmp, item, index) => {
// 不是最后一次
if (index != scoreone.length - 1) {
console.log(index)
return tmp + item;
} else {
// 最后一次
return (tmp + item) / scoreone.length;
}
});
alert(resultone);
</script>
</head>
<body>
</body>
</html>
2.3 分析图
3.fliter 过滤器
3.1 个人理解
3.2 代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>filter过滤器</title>
<script>
let score = [12, 88, 59, 99];
// let result = score.filter((item) => {
// alert(item % 3 == 0);
// if (item % 3 == 0) {
// return true;
// } else {
// return false;
// }
// });
// 简写
let result = score.filter(item => item % 3 == 0 ? true : false);
alert(result);
let arr = [{
title: '男士衬衫',
price: 75
}, {
title: '衬衫',
price: 65000
}, {
title: '男士',
price: 2250
}];
let resultone = arr.filter(item => item.price > 1000 ? true : false);
console.log(resultone);
// console.log(resultone[0].title);
</script>
</head>
<body>
</body>
</html>
4.forEach 循环(迭代)
4.1 个人理解
4.2 代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>forEach迭代循环</title>
<script>
let score = [12, 88, 59, 99];
score.forEach((item, index) => {
alert(index + ":" + item);
});
</script>
</head>
<body>
</body>
</html>