Javascript:使用地图在每个循环中迭代多个项目 [英] Javascript: Iterating over multiple items per loop with map

查看:24
本文介绍了Javascript:使用地图在每个循环中迭代多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿也可以

让我们说我有一个像这样的数组

Lets say I have an array like this

const array = ['one', 'two', 'three', 'four', 'five']

我想生成一些看起来像

  <div>
    one
    two
  </div>
  <div>
    three
    four
  </div>
  <div>
    five
  </div>

如果我想使用map函数,就我所知,我将不得不写类似

If I wanted to use the map function, to the best of my knowledge I would have to write something like

{
  let saved
  array.map((item) => {
    if (saved === ''){
      let temp = saved
      saved = ''
      return (  
        <div>{`${item} ${temp}`}</div>
      )
    }else{
      saved = item
    }
  })
}

但是我想稍微清理一下这段代码.我正在寻找一种方法,可以使用map函数(或forEach)遍历一次移动超过2个项目的数组,以便可以将上面的代码缩短为下面的代码,并产生相同的结果

But I would like to clean this code up a bit. I'm looking for a way that I can use the map function(or forEach) to iterate over the array moving across 2+ items at a time, so that the above code could be shortened to something like below, and produce the same result.

array.map((item1, item2) => <div>{`${item1} ${item2}`}</div>)

推荐答案

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
let arr=chunk([1, 2, 3, 4, 5], 2);

arr.map(item=> item.length>1 ? `<div>${item[0]}${item[1]}</div>` : `<div>${item[0]}</div>` )

使用lodash块方法跟随此链接

这篇关于Javascript:使用地图在每个循环中迭代多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆