当前位置:网站首页>js中map和forEach的用法
js中map和forEach的用法
2022-07-02 06:40: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
边栏推荐
猜你喜欢

js中对于返回Promise对象的语句如何try catch

ZZQ的博客目录--更新于20210601

Uploading attachments using Win32 in Web Automation

华为MindSpore开源实习机试题

Cglib agent - Code enhancement test

CUDA中的Warp Shuffle

蚂蚁集团g6初探

Detailed definition of tensorrt data format

Introduce two automatic code generators to help improve work efficiency

Sentinel rules persist to Nacos
随机推荐
Latex 报错 LaTeX Error: The font size command \normalsize is not defined问题解决
Pytest (1) case collection rules
Vector types and variables built in CUDA
Code skills - Controller Parameter annotation @requestparam
sprintf_ How to use s
CUDA用户对象
Function execution space specifier in CUDA
The intern left a big hole when he ran away and made two online problems, which made me miserable
DeprecationWarning: .ix is deprecated. Please use.loc for label based indexing or.iloc for positi
【文献阅读与想法笔记13】 Unprocessing Images for Learned Raw Denoising
Find the highest value of the current element Z-index of the page
ctf-web之练习赛
FE - Eggjs 结合 Typeorm 出现连接不了数据库
CUDA与Direct3D 一致性
利用NVIDIA GPU将Minecraft场景渲染成真实场景
分布式事务 :可靠消息最终一致性方案
Loops in tensorrt
压力测试修改解决方案
Kotlin - 验证时间格式是否是 yyyy-MM-dd HH:mm:ss
ModuleNotFoundError: No module named ‘jieba.analyse‘; ‘jieba‘ is not a package