当前位置:网站首页>JS中数组的遍历方法有哪些
JS中数组的遍历方法有哪些
2022-07-27 05:03:00 【weixin_46051260】
1)forEach:不会改变原数组,没有返回值
三个参数,遍历值,索引值,数组本身
var arr=[1,2,3,4,5,6]
arr.forEach(item=>{
console.log(item);
//没有返回值
return item*2//undefined
})
2)map:不会改变原数组,有返回值
参数和forEach一样
var arr=[1,2,3,4,5,6]
const arrMap=arr.map(item=>{
console.log(item);
//没有返回值
return item*2
})
console.log(arrMap);//[2,4,6,8,10,12]
3)filter:过滤数组,有返回值,返回包含符合条件的元素的数组,不会改变原数组
参数和forEach一致
var arr=[1,2,3,4,5,6]
const arrFilter=arr.filter(item=>{
console.log(item);
//没有返回值
return item<5
})
console.log(arrFilter);//[1,2,3,4]
4)for…of…:返回的是数组的元素,对象的属性值,不能遍历普通对象
var arr =[1,2,3,4,5]
for(let value of arr){
console.log(value);//返回键值
}
5)reduce:接收一个函数,作为一个累加器,不改变原数组
函数有四个参数,但是两个参数最为常用,而且必须写,第一个返回计算之后的值或者初始值,第二个为当前元素
var arr=[1,2,3,4]
var arrReduce=arr.reduce((pre,item)=>{
return pre+item
},0)//此处0为第一个参数的初始值
console.log(arrReduce);//10
边栏推荐
- Li Hongyi machine learning team learning punch in activity day05 --- skills of network design
- Redis lock
- 通用视图,DRF视图回顾
- Pytorch installation new pit
- Introduction to C language pointer
- Pinball games
- C language string function: strlen, strcpy, strcat
- C WPF uses listbox to implement ruler control
- cmd命令和npm命令
- How to quickly and effectively solve the problem of database connection failure
猜你喜欢

Source code of document type full-text retrieval knowledge base management system

函数和箭头函数

First knowledge of C language -- constants and variables

用户的管理-限制

Flask请求数据获取与响应

程序环境和预处理(下):#define、#undef、命令行编译、条件编译、文件包含(超全整理,建议收藏!!!

First knowledge of C language - string + escape character + comment

元素显示模式:块级,行内,行内块,嵌套规范,显示模式转换

分享一道关于#define的选择题(内含#define在预编译时的替换规则,程序环境和预处理相关知识)

初识C语言——什么是C语言
随机推荐
Share a multiple-choice question about the process of program compilation (including a brief discussion on the compilation process, the formation and merging process of symbol tables)
c语言字符串函数下:strcmp、strncpy、strncat、strncmp、strstr、strtok、strerror
背景图片相关应用-铺满,自适应
Day6 --- SQLAlchemy进阶
JS中apply、call、bind的区别
软件测试面试题(重点)
流程控制-分支
JS中是如何使用for..of来遍历对象
JS中arguments类数组
后台实现spu管理
Flask对模型类的操作
Share a multiple-choice question about variables (including global variables, local variables, the scope of variables, and life cycle knowledge points)
进制的特性
【codeforces round#800 B. Paranoid String】DP
初识C语言——常见的数据类型
[C language switch branch statement and loop statement]
elment-ui使用方法
Looking at the PK of alphago and Li Shishi from a deep perspective
Promise的理解,以及它的实例方法
分享力扣—189.轮转数组 的三种解法