1

#yyds干货盘点# 歌谣学前端之数组的方法

 1 year ago
source link: https://blog.51cto.com/u_14476028/5911541
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# 歌谣学前端之数组的方法

精选 原创

前端歌谣 2022-12-05 10:40:25 ©著作权

文章标签 数组 回调函数 html 文章分类 JavaScript 前端开发 阅读数202

我是歌谣 我有个兄弟 巅峰的时候排名c站总榜19 叫前端小歌谣 曾经我花了三年的时间创作了他 现在我要用五年的时间超越他 今天又是接近兄弟的一天人生难免坎坷 大不了从头再来 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷 微信公众号前端小歌谣

常用数组方法简单使用

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>数组的方法</title>
<script>

const arr = [1, 2, 3, 4, 5];

/*
* map()
* - 可以根据原有数组返回一个新数组
* - 需要一个回调函数作为参数,回调函数的返回值会成为新数组中的元素
* - 回调函数中有三个参数:
* 第一个参数:当前元素
* 第二个参数:当前元素的索引
* 第三个参数:当前数组
*
* filter()
* - 可以从一个数组中获得符和条件的元素
* - 会根据回调函数的结果来决定是否保留元素,true保留,false不保留
*
* find()
* - 可以从一个数组中获得符和条件的第一个元素
*
* reduce()
* - 可以用来合并数组中的元素
* - 需要两个参数:
* 回调函数(指定运算规则)
* 四个参数:
* prev 上一次运算结果
* curr 当前值
* index 当前索引
* arr 当前数组
* 初始值
* - 用来指定第一次运算时prev,如果不指定则直接从第二个元素开始计算
* */
let result = arr.map((item) => {
return item + 2;
});

result = arr.map((item, index, array) => {
return item + 2;
});

// console.log(result);

const arr2 = ['孙悟空', '猪八戒', '沙和尚'];
/*
* <li>孙悟空</li>
* <li>猪八戒</li>
* <li>沙和尚</li>
* */

result = arr2.map(item => "<li>" + item + "</li>");


result = arr.filter(item => item % 2 === 0);
result = arr.find(item => item % 2 === 0);


result = arr.reduce((prev, curr, index) => {
console.log(index, prev, curr);
return prev + curr
},0);
console.log(result);


</script>
</head>
<body>

</body>
</html>
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK