当前位置:网站首页>js中map和forEach的用法
js中map和forEach的用法
2022-07-02 06:22:00 【秦时明月之安康】
前言
编码过程中一直分不清map和forEach的区别,闲下来,弄几个例子研究一下。
一、map
1.简单数组
const a = [ 5, 7, 10, ]
const mapA = a.map((item, index, arr) => {
console.log(item, index, arr)
return item * 2
})
console.log(mapA)
输出:
2.对象数组
const c = [
{
key: 'key1',
value: 'value1',
},
{
key: 'key2',
value: 'value2',
},
]
const mapC = c.map((item, index, arr) => {
console.log(item, index, arr)
let res = this.$deepCopy(item)
res.value += index
return res
})
console.log(c)
console.log(mapC)
输出:
所以事实上map不仅可以遍历数组,还可以返回一个新数组。
3.修改简单数组内容
const a = [ 5, 7, 10, ]
const mapA = a.map((item, index, arr) => {
console.log(item, index, arr)
arr[index] = item * 2
return item * 2
})
console.log(a)
console.log(mapA)
输出:
4.修改对象数组内容
const c = [
{
key: 'key1',
value: 'value1',
},
{
key: 'key2',
value: 'value2',
},
]
const mapC = c.map((item, index, arr) => {
console.log(item, index, arr)
let res = item
res.value += index
return res
})
console.log(c)
console.log(mapC)
输出:
可见,对象数组在遍历的过程中,修改属性的值就可以影响到原数组
map的其他用法详见文档
二、forEach
1.简单数组
const a = [ 5, 7, 10, ]
a.forEach((item, index, arr) => {
arr[index] = item * 2
console.log(item, index, arr)
})
console.log(a)
输出:
2.对象数组
const c = [
{
key: 'key1',
value: 'value1',
},
{
key: 'key2',
value: 'value2',
},
]
c.forEach((item, index, arr) => {
console.log(item, index, arr)
item.value += index
})
console.log(c)
输出:可见,对象数组在遍历的过程中,修改属性的值就可以影响到原数组
3.forEach() 的 continue 与 break
边栏推荐
- Uploading attachments using Win32 in Web Automation
- Introduce two automatic code generators to help improve work efficiency
- 20201025 Visual Studio2019 QT5.14 信号和槽功能的使用
- Redis - grande question clé
- Fe - weex uses a simple encapsulated data loading plug-in as the global loading method
- Golang--map扩容机制(含源码)
- Pytest (2) mark function
- MySQL的10大經典錯誤
- Shardingsphere JDBC
- web自动中利用win32上传附件
猜你喜欢
Sublime Text 配置php编译环境
Win10网络图标消失,网络图标变成灰色,打开网络设置闪退等问题解决
FE - 微信小程序 - 蓝牙 BLE 开发调研与使用
Linked list (linear structure)
pytest(1) 用例收集规则
Redis - hot key issues
Latex 报错 LaTeX Error: The font size command \normalsize is not defined问题解决
web自动中利用win32上传附件
Uploading attachments using Win32 in Web Automation
[literature reading and thought notes 13] unprocessing images for learned raw denoising
随机推荐
默认google浏览器打不开链接(点击超链接没有反应)
Warp shuffle in CUDA
Learn about various joins in SQL and their differences
eslint配置代码自动格式化
Shardingsphere JDBC
Présence d'une panne de courant anormale; Problème de gestion de la fsck d'exécution résolu
Summary of WLAN related knowledge points
TensorRT的命令行程序
FE - weex 开发 之 使用 weex-ui 组件与配置使用
【张三学C语言之】—深入理解数据存储
TensorRT的功能
【每日一题】—华为机试01
NodeJs - Express 中间件修改 Header: TypeError [ERR_INVALID_CHAR]: Invalid character in header content
[self cultivation of programmers] - Reflection on job hunting Part II
【每日一题】写一个函数,判断一个字符串是否为另外一个字符串旋转之后的字符串。
Sublime Text 配置php编译环境
virtualenv和pipenv安装
Linked list (linear structure)
Tensorrt command line program
由於不正常斷電導致的unexpected inconsistency;RUN fsck MANUALLY問題已解决