我是 Javascript 新手
let n = 10;
nextPrime:
for (let i = 2; i <= 60; i ) {
for (let j = 2; j < i; j ) {
if (i % j == 0) continue nextPrime;
}
console.log ( i );
}
console.log("Total of prime numbers found:", n.length)
不明白為什么 console.log("找到的素數總數:", n.length) undefined :(
uj5u.com熱心網友回復:
在您的代碼中,您試圖獲取 .length 的 n 變數,它是一個數字,而不是變數的串列型別。
所以要更正代碼:
只需洗掉 .length
最終代碼:
let n = 10;
nextPrime:
for (let i = 2; i <= 60; i ) {
for (let j = 2; j < i; j ) {
if (i % j == 0) continue nextPrime;
}
console.log ( i );
}
console.log("Total of prime numbers found:", n);
uj5u.com熱心網友回復:
你找不到數字的長度(讓 n = 10 // n 是數字)
長度參考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length
https://www.w3schools.com/jsref/jsref_length_array.asp
https://www.w3schools.com/jsref/jsref_length_string.asp
uj5u.com熱心網友回復:
這應該有效,但分配一個陣列。我看到代碼有兩個問題:
- 您正在嘗試對
length產生錯誤的數字使用方法。 - 您不會做任何
n不會使其計算素數的實際數量的更改。
let arr = []
function checkprime(num) {
for (let j = 2; j < num; j ) {
if (num % j == 0)
return false;
}
return true;
}
for (let i = 2; i <= 60; i ) {
if (checkprime(i)) {
arr.push(i)
}
}
console.log("Total of prime numbers found:", arr.length);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/405760.html
標籤:
上一篇:檢查一個物件是否是另一個物件的原型的最佳方法是什么?
下一篇:反應路線問題(呈現空白頁面
