我有许多数组,需要根据所请求的页面从中提取值。每个页面都需要分配一个唯一的数据组合,例如:
let numbers = ['One', 'Two']
let fruits = ['Apples', 'Oranges']
let colours = ['Red', 'Green']
let names = ['John', 'Jane']
没有一个数组会是空的,因此可用页面的数量将是所有数组的长度彼此相乘(因此在本例中,totalPages 将为 16
let totalPages = numbers.length * fruits.length * colours.length * names.length
对于请求的每个页面,我需要返回一组唯一的索引,以便每个页面显示一组不同的值,并且每组中的值不会超过一个。
我目前有嵌套的 for 循环(下面的示例),但我想知道是否有一种更简洁的方法使用 mod 运算符或其他东西,这样我就不需要依赖 for 循环,因为在某些时候我可能会需要引入额外的数组,而且我讨厌嵌套循环的外观......
let page = 4 // The requested page (not zero-based index)
let nPage = 1
for(let numberIndex = 0; numberIndex < numbers.length; numberIndex ++) {
for(let fruitIndex = 0; fruitIndex < fruits.length; fruitIndex ++) {
for(let colourIndex = 0; colourIndex < colours.length; colourIndex ++) {
for(let nameIndex = 0; nameIndex < names.length; nameIndex ++) {
// If the loop iteration matches the requested page,
// return the combination of indexes as array
if(page === nPage) {
return [numberIndex, fruitIndex, colourIndex, nameIndex]
}
nPage ++
}
}
}
}
提前感谢您的任何想法/建议:o)
最佳答案
这确实是一个数学/算法问题(这总是很有趣!)。所以一个好的方法是看看你是否能找出这个模式。例如,给定 3 个数组,[1,2,3,4]
、[x,y,z]
和 [11,12]
>,你期待
1 x 11
2 x 11
3 x 11
4 x 11
1 y 11
2 y 11
3 y 11
4 y 11
1 z 11
2 z 11
3 z 11
4 z 11
1 x 12
2 x 12
3 x 12
4 x 12
1 y 12
2 y 12
3 y 12
4 y 12
1 z 12
2 z 12
3 z 12
4 z 12
现在模式应该很清楚了,它只是在计数,就像您数1,2,3,...9,10,11...99,100,101...
。但在传统计数中,所有数字都从 0 开始,到 10 换行。而在我们的示例中,第一个数字从 1 开始,到 4 换行;第二个数字从“x”开始并在“z”处环绕,第三个数字从“11”开始并在 12 处环绕。
如果有人要求你找到第 m 个 4 位十进制数的第 n 位(从右数)(例如 1234 的第 3 位是 2),你可以用 temp = Floor chop (m/10 ** (n-1))
,这将为您提供 1234, 123, 12, 1。然后 temp % 10
将给出每个的最后一位数字:4, 3、2、1。
在我们的例子中,我们的数字不是以 10 为基数,因此我们用适当的计算替换 10:
let numbers = ['1', '2', '3'];
let fruits = ['a', 'b', 'c'];
let colours = ['x', 'y', 'z'];
let names = ['11', '12', '13'];
let getPage = i =>
[
numbers[i % numbers.length],
fruits[Math.floor(i / numbers.length) % numbers.length],
colours[Math.floor(i / numbers.length / fruits.length) % colours.length],
];
// print only the first 40 pages, otherwise stackoverflow will truncate the console
for (let i = 0; i < 40; i++)
console.log(getPage(i).join(' '));
如果您有一组动态数组(例如,您提前不知道将使用哪些数组):
let numbers = ['1', '2', '3'];
let fruits = ['a', 'b', 'c'];
let colours = ['x', 'y', 'z'];
let names = ['11', '12', '13'];
let getPage = (pageI, arrays) => {
// `pageCounts[i]` is the # of combinations that can generated from the 1st `i` arrays.
let pageCounts = arrays.map((values, j) => arrays
.filter((_, k) => k < j)
.map(a => a.length)
.reduce((a, b) => a * b, 1));
return arrays.map((values, j) => values[Math.floor(pageI / pageCounts[j]) % values.length]);
};
// print only the first 40 pages, otherwise stackoverflow will truncate the console
for (let i = 0; i < 40; i++)
console.log(getPage(i, [numbers, fruits, colours, names]).join(' '));
关于javascript - 使用 Mod 运算符对多个数组进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70883809/