【问题标题】:Converting forEach function to map function in JavaScript在 JavaScript 中将 forEach 函数转换为 map 函数
【发布时间】:2017-10-20 06:28:54
【问题描述】:

这是我当前使用forEach()的代码:

1.

// loop with assignment
userForm.forEach(field => {
    field.value = ''
})

2.

// if array1 has field which array2 have, assign it
array1.forEach(field => {
    if (Object.keys(array2).indexOf(field.name) > -1) {
      field.value = array2[field.name]
    }
})

3.

array1.forEach(field => {
    field.shouldShow = false
    field.start = moment(invoice.start).format('YYYY/MM/DD')
    field.end = moment(invoice.end).format('YYYY/MM/DD')
    // ..brabrabra asignment
})

是否可以将所有forEach() 函数转换为map() 函数?

【问题讨论】:

  • 不清楚你想要达到什么目的
  • 当你遍历对象并且只改变它的属性时,它并没有太大的区别。使用地图时,您必须添加return field
  • 想让它更实用,比如:array1.map(field => xxxxxx)
  • @KevinHu 我读到你想将forEach 转换为map,但你想在循环中实现什么?第一个和第三个可以很容易地完成,但第二个可能不合适。那么,用例是什么?你想达到什么目的?
  • function emailClients(clients) { clients.filter(isClientActive) .forEach(email) } function isClientActive(client) { var _clientRecord = database.lookup(client);返回 _clientRecord.isActive();我应该这样改变吗?

标签: javascript for-loop foreach ecmascript-6


【解决方案1】:

用法

foreach:遍历一个列表并对每个列表成员应用一些具有副作用的操作(例如:将每个列表项保存到数据库中)

map:遍历一个列表,转换该列表的每个成员,并返回另一个与转换后的成员大小相同的列表(例如:将字符串列表转换为大写)

参考文献

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEachhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

【讨论】:

    【解决方案2】:

    在网上找到这个试试

    var m = new Map();  
    m.set(1, "car");  
    m.set(2, "bike");  
    m.set("colors", 2);  
    m.set({x:1}, 3);  
    
    m.forEach(function (item, key, mapObj) {  
        document.write(item.toString() + "<br />");  
    });  
    
    document.write("<br />");  
    document.write(m.get(2));  

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-17
      • 2016-06-02
      • 2021-11-25
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 2022-01-04
      • 2016-11-26
      相关资源
      最近更新 更多