gpt4 book ai didi

javascript - React js 中的环绕

转载 作者:行者123 更新时间:2023-12-03 02:13:41 25 4
gpt4 key购买 nike

const data1 = [
{ name: 'one' },
{ name: 'two' },
{ name: 'three' },
{ name: 'four' },
{ name: 'five'},
{ name: 'six'}
];


const colors = ['red', 'purple', 'violet', 'blue'];

我想要这种格式的输出---

  render(){...
<Button color="from array colors">//Values from data1 here</Button>

这是我拥有的两个数组。现在我的问题是如何以环绕方式访问颜色,即 data1 的“五个”应该用颜色[0]着色。请帮助,因为我是 React 新手。

最佳答案

如果通过wraparound,您的意思是在第5个元素上选择颜色[0],因为只有4种颜色,您可以使用modulo %

喜欢:

const data1 = [
{ name: 'one' },
{ name: 'two' },
{ name: 'three' },
{ name: 'four' },
{ name: 'five'},
{ name: 'six'}
];

const colors = ['red', 'purple', 'violet', 'blue'];

data1.forEach((v, i) => {
let color = colors[i % colors.length];

//Construct HTML and console for testing
console.log('<Button color="' + color + '">' + v.name + '</Button>');
});

关于javascript - React js 中的环绕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49445285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com