我试图优雅地解决这个问题,但我想我只是让自己感到困惑。使用任意长度和内容的数组输入(例如,[0,1,2,3,4,5,...]
)我希望输出为:
[
{ slide: 0, style: 'A' },
{ slide: 1, style: 'A' },
{ slide: 2, style: 'B' },
{ slide: 3, style: 'B' },
{ slide: 4, style: 'A' },
{ slide: 5, style: 'A' },
{ slide: 6, style: 'B' },
{ slide: 7, style: 'B' },
{ slide: 8, style: 'A' },
{ slide: 9, style: 'A' },
{ slide: 10, style: 'B' },
{ slide: 11, style: 'B' },
...
]
所以只重复A A B B
模式。
这是我尝试过的,但经过几次迭代后似乎会崩溃。
const slides = [...Array(24).keys()];
const getStyleForIndex = (index) => {
if ((index) % 4 === 0 || (index) % 5 === 0 || index === 1) {
return 'A';
}
return 'B';
};
const newSlides = slides.map((slide, index) => ({ slide: slide, style: getStyleForIndex(index) }));
console.log(newSlides);

非常感谢任何争论模数运算符的帮助!
答案 0 :(得分:4)
在这两种情况下你应该使用index % 4
,而不是index % 5
。这将返回一系列循环遍历0, 1, 2, 3
的数字。
if (index % 4 == 0 || index % 4 == 1) {
return 'A';
} else {
return 'B';
}
或更简单:
return index % 4 < 2 ? 'A' : 'B';
答案 1 :(得分:1)
您可以通过位移和检查奇数来采用不同的方法。
移位取数字并除以2(由于两个相同的值按顺序排列)并取整数值,下一次检查用于检查组。
var i = 0;
while (i < 10) {
console.log(i, i >> 1 & 1 ? 'B' : 'A');
i++;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }