使用map遍历两个数组 [英] Using map to iterate through two arrays

查看:73
本文介绍了使用map遍历两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前在React中,我正在使用 array.map(function(text,index){})遍历数组.但是,我要如何使用map同时遍历两个数组?

Currently in React, I am using array.map(function(text,index){}) to iterate through an array. But, how am I going to iterate through two arrays simultaneously using map?

编辑

var sentenceList = sentences.map(function(text,index){
            return <ListGroupItem key={index}>{text}</ListGroupItem>;
        })
return (
     <div>
       <ListGroup>
        {sentenceList}
      </ListGrouup>
   </div>
);

就像,在此我希望图标在每次迭代之前都带有前缀.我计划将这些图标放在另一个数组中.因此,这就是为什么要迭代两个数组的原因.

Like, in this I want icons to be prepended with every iteration. And I'm planning to have those icons in another array. So, thats why iterate two arrays.

推荐答案

如果可能的话,我建议将文本与图像一起存储在对象数组中,例如:

If at all possible, I would recommend storing the text alongside the images in an array of objects, eg:

const objects = [{text: 'abc', image: '/img.png' }, /* others */];

这样,您就可以遍历数组并同时选择两个成员,例如:

that way you can just iterate through the array and select both members at the same time, for example:

objects.map(item => (<Component icon={item.image} text={item.text} />) )

如果这不可能,则只需映射一个数组并通过当前索引访问第二个数组的成员:

If this isn't possible then just map over one array and access the second array's members via the current index:

sentences.map((text, index) => {
    const image = images[index];
    return (<Component icon={image} text={text} />);
});

这篇关于使用map遍历两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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