我有两个长度可变的数组,我想实现一种模式,我已经实现了,但对我的解决方案不满意。我相信可能有更好的方法来实现这一目标。
const logic = (outerArray, innerArray) => outerArray.map((outerVal, OuterIndex) => {
return innerArray.map((innerVal, innerIndex) => {
const currentSlideIndex = OuterIndex + 1;
if (innerArray.length < 6 && innerIndex + 1 === currentSlideIndex) return true;
if (innerArray.length === 6) {
if (innerIndex < 4 && innerIndex + 1 === currentSlideIndex) return true;
// return false if currentslide is greater than four and less than last two slides
if (currentSlideIndex > 4 && currentSlideIndex < outerArray - 1 && innerIndex === 3) {
return true;
}
if (innerIndex === 4 && currentSlideIndex === outerArray - 1) return true;
if (innerIndex === 5 && currentSlideIndex === outerArray) return true;
}
return '';
});
});
预期成果
-
如果 innerArray 长度小于或等于 6,它应该返回长度数组作为 innerArray,并且输出应该看起来像
逻辑([1,2,3,4,5],[1,2,3,4,5](
预期产出
[ [true, "", "", "", ""], ["", true, "", "", ""], ["", "", true, "", ""], ["", "", "", true, ""], ["", "", "", "", true] ]
-
如果 outerArray 长度大于 6,那么它应该对 3 个索引工作相同,对于所有 outerArray 索引,应该对索引 4 返回 true,并在最后两个索引处恢复。
逻辑([1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6](
预期产出
[ [true,"","","","",""], ["",true,"","","",""], ["","",true,"","",""], ["","","",true,"",""], ["","","",true,"",""], ["","","",true,"",""], ["","","",true,"",""], ["","","",true,"",""], ["","","","",true,""], ["","","","","",true] ]
我会将您的代码分成两个函数。第一个将返回 outerArray 的每个值的列索引,如下所示:
const getColumnIndexes = (array) => {
// Get first 3 items
let columnIndexes = array.slice(0, 3);
// Get items in 4th column
columnIndexes = columnIndexes.concat(array.slice(3, Math.max(4, array.length - 2)).map(() => 4));
// Get last 2 items
columnIndexes = columnIndexes.concat(array.slice(Math.max(4, array.length - 2), array.length).map((val, index) => 5 + index));
return columnIndexes;
};
然后你的logic
函数变得非常简单:
const logic = outerArray => {
const columnIndexes = getColumnIndexes(outerArray);
return outerArray.map((val, lineIndex) => {
return Array(Math.min(6, outerArray.length)).fill().map((_, i) => i === columnIndexes[lineIndex] - 1 ? true : "");
});
};
如果我理解正确,你实际上不再需要这个内部数组了。
logic([1, 2, 3, 4, 5]);
[
[true, "", "", "", ""],
["", true, "", "", ""],
["", "", true, "", ""],
["", "", "", true, ""],
["", "", "", "", true]
]
logic([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
[
[true,"","","","",""],
["",true,"","","",""],
["","",true,"","",""],
["","","",true,"",""],
["","","",true,"",""],
["","","",true,"",""],
["","","",true,"",""],
["","","",true,"",""],
["","","","",true,""],
["","","","","",true]
]