[英]I need to create a Logic that creates a new loop per item based on the Input Array
我需要創建一個嵌套邏輯,循環數基於輸入數組長度。
這個數組可以有 N 個值,數組的名稱是 penalities,我需要根據這些交互來制定我的邏輯。
如果輸入數組長度 N 為 3,如懲罰數組 [1, 2, 3]
我的代碼需要結果
for (let x = 1; x <= 2; x += 0.1) {
for (let y = 1; y <= 2; y += 0.1) {
for (let z = 1; z <= 2; z += 0.1) {
const penalities = [x, y, z];
myFunction(penalities);
}
}
}
enter code here
如果輸入數組長度 N 為 4,如 penalities array= [1, 2, 3, 4]
我的代碼需要結果
for (let x = 1; x <= 2; x += 0.1) {
for (let y = 1; y <= 2; y += 0.1) {
for (let z = 1; z <= 2; z += 0.1) {
for (let k = 1; k <= 2; k += 0.1) {
const penalities = [x, y, z, k];
myFunction(penalities);
}
}
}
}
如何使這個迭代邏輯通用以接收數組內的任何數量,而不必創建 N 嵌套。
您可以采用遞歸方法並為每個循環的值采用索引數組。
function iterate(array, cb) { function iter(index) { for (let i = 0, l = array[index]; i < l; i++) { indices[index] = i; if (index + 1 === array.length) cb(indices); else iter(index + 1); } } const indices = []; iter(0); } iterate([3, 2, 2, 4], indices => console.log(...indices));
.as-console-wrapper { max-height: 100%;important: top; 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.