我的代碼適用于某些輸入,但適用于這樣的輸入: ('This' 'painting' '1845 and 1910') 我收到一個錯誤:AssertionError 7 == 8。我可以使用正則運算式解決它,但我沒有'不知道我在做什么錯。謝謝回答。
import assert from "assert";
function countDigits(text){
let num = text.split('');
let sum = 0;
for (let i=0; i<num.length; i ){
if (Number(num[i])) {
sum = 1;}}
return sum
}
assert.equal(countDigits('This'
'painting'
'1845 and 1910'), 8);
uj5u.com熱心網友回復:
Number(num[i])將包括"0"轉換為數字,但在 Javascript 的 if 條件下,它將是虛假的
if(Number("0")) {
console.log('true') //you're expecting this because it's a number
} else {
console.log('false') //but in fact, it returns this because 0 is falsy
}
在這種情況下,我建議您使用isNaN(num[i])
function countDigits(text) {
let num = text.split('');
let sum = 0;
for (let i = 0; i < num.length; i ) {
//num[i] = " " will be considered a number, so we need to check it as well
if (num[i] !== " " && !isNaN(num[i])) {
sum = 1;
}
}
return sum
}
console.log(countDigits('This'
'painting'
'1845 and 1910'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/481661.html
標籤:javascript
上一篇:當我設定寬度時,子元素消失
