[英]Why am I getting one empty array item in every other array like a pattern? (JavaScript)
在帖子底部更新!
只有可以一次性制作的星形多邊形,即像五角星一樣,而不像只能用至少 2 個形狀(即 2 個倒置和重疊三角形)制作的六角星。
我幾乎完成了這個。 一切似乎都運行良好,我得到了我想要的輸出,除了由於某種原因在每個其他數組中都有一個空數組項。
我正在將一個對象打印到控制台(用於測試),其中的項目以數字命名,這些數字代表正多邊形的點/邊數。 在每個項目中是一個數組,其中包含該項目的所有非因式分解數字的下半部分(數字),即一個數字數組,當數字(項目名稱)除以它們時,它將返回一個分數。
例如對象
points變量(例如= 8)被發送到一個函數( qty_test ),該函數用於查找我需要測試的除數並在其中除以 2。如果結果是分數,它將返回結果四舍五入,如果是偶數,它將返回結果 - 1。
//8 has more divisors to cycle through -so its a better example!
//In the real program, it will be 5.
let points = 8;
let starPolygons = {};
例如 qty_test
function qty_test(n) {
n /= 2;
let divisorQTY = n - Math.floor(n) !== 0;
return divisorQTY ? Math.floor(n) : (n - 1);
};
此函數使用從前一個函數 ( n ) 返回的數字來設置一個 for 循環,如果n不是points變量值的一個因子,則該循環測試每個循環。 即點除以n返回一個分數,如果它返回 true,則意味着生成了一個分數n `s 值在數組中被索引並減 1 ( --n )。
例如除數測試
function divisor_test(n) {
let nonFactors = [];
n = qty_test(n);
for (let index = 0; index <= n; index++) {
let quotient = (points / n) - Math.floor(points / n) !== 0;
quotient ? nonFactors[index] = n-- : --n;
};
return nonFactors;
};
該程序在 5 - 360 之間循環,並用數字 (5-360) 和它們的下半部分非因子數字的數組列表來索引一個對象。
while (points <= 360) {
nonFactors = divisor_test(points);
let testArray = nonFactors.length;
if (testArray) starPolygons[String(points)] = nonFactors;
points++;
};
console.log(starPolygons);
正如您在這張圖片中看到的那樣。 空數組索引/項的模式
在迭代期間,您強制數組添加一個空項。 因此,當數組中只有兩個項目並且您嘗試 nonFactors[3] = n--; 時,會出現空對象這就是導致問題的原因。
因此,帶有解決方案的 for 循環的更簡化版本將是
for (let index = 0; index <= n; index++) {
let quotient = (points / n) - Math.floor(points / n) !== 0;
if(quotient){
if(index > nonFactors.length){
nonFactors[index - 1] = n--
}else{
nonFactors[index] = n--
}
}else{
n = n -1;
}
};
這里有一個答案已經解釋了導致問題的原因,並且還提供了 Nadav Hury 的可行解決方案(支持他的答案。我敢打賭他的答案通常在更多情況下效果更好)! 所以我只會發布我自己的解決方案版本。
for (let index = 0; n >= 2; index++) {
let quotient = (points / n) - Math.floor(points / n) !== 0;
if (quotient) nonFactors[index] = n--;
else --n, --index;
};
罪魁禍首是與檢查商一致
quotient ? nonFactors[index] = n-- : --n;
您添加了僅在它存在等於 true 的情況下設置值,但當它是 false 時您沒有添加到情況下,正確的解決方案是:
quotient ? nonFactors[index] = n-- : nonFactors[index] = --n;
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.