此函式應計算字串中的“a”并計算所有“a”之和與字串長度之間的比率。它作業正常,除非字串為空并且它應該輸出“0”而不是NaN。那'
function ratio(statistic) {
let charcount = 0 ;
for ( let i = 0 ; i < statistic.length ; i ){
if ( statistic[i] == 'a' ){ charcount = 1 ;}
}
return Math.round(charcount/statistic.length * 100) ;
}
console.log(ratio('abababaabaaa'));
console.log(ratio(''));
// 67
// NaN <---- here should be 0
是我想要解決的問題,謝謝。
uj5u.com熱心網友回復:
當您有空字串或空字串時, 的值為statistic.length0。因此您的代碼中缺少此檢查,這就是您得到 NaN(非數字)的原因。
function ratio(statistic) {
let charcount = 0 ;
for ( let i = 0 ; i < statistic.length ; i ){
if ( statistic[i] == 'a' ){ charcount = 1 ;}
}
// Corrected code here
return statistic.length == 0 ? 0 : Math.round(charcount/statistic.length * 100) ;
}
console.log(ratio('abababaabaaa'));
console.log(ratio(''));
// 67
// NaN <---- here should be 0
uj5u.com熱心網友回復:
嘗試:
function ratio(statistic) {
let charcount = 0 ;
for ( let i = 0; i < statistic.length; i ) {
if ( statistic[i] == 'a' ) { charcount = 1; }
}
if (charcount === 0) return 0; // check if there were no a's in the string, if so return 0
return Math.round(charcount/statistic.length * 100) ;
}
console.log(ratio('bbbbbbbaaa'));
console.log(ratio(''));
為了避免除以 0,我們只檢查是否沒有找到 a,如果是則回傳 0。
uj5u.com熱心網友回復:
您可以使用正則運算式來計算所需字符的匹配數量。(statistic.match(/a/g)||[]).length您可以在其中更改任何字符的“a” (取自此處)
NaN 問題正在發生,因為如果字串長度為零,則您將除以 0/0。那是一種數學上的不定形式。要解決這個問題,您應該首先檢查字串是否為空statistic.length > 0。
let ratio = (statistic) => statistic.length > 0 ? Math.round((statistic.match(/a/g)||[]).length / statistic.length * 100) : 0;
console.log(ratio('abababaabaaa'));
console.log(ratio(''));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426014.html
標籤:javascript 细绳
