首页 > 解决方案 > 如何计算字符串中的数字?

问题描述

我的代码就是这样..我正在使用isNaN()但问题仍然有效

function numberSearch (str) {
    let sum = 0;
    let strCount = 0;
    
    if(str === "") {
        return 0;
    };
  
    for(let i = 0 ; i < str.length; i++) {
        if (isNaN(Number(str[i]))) {
            strCount = strCount + 1   // if it's true, +1
        }
        sum = sum + Number(str[i])
    } 
    return Math.round(sum/strCount);
}
let output = numberSearch('Hello6 ');
console.log(output); // --> 1

output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1

我如何计算数字并计算它?

我正在使用isNaN(),但是当我使用调试器总和为'NaN'时,我不能很好地对待..我不能很好地理解..

标签: javascript

解决方案


滚动查看已编辑问题的答案。

NaN === NaN

将是错误的,这里给出了一个很好的解释。

尝试使用isNaN()检查而不是比较。

编辑:据我了解,您希望获得字符串中找到的数字的四舍五入平均值。相应地if修改检查 - 如果有一个数字被检查,它必须增加计数和总和:

function numberSearch (str) {
    let sum = 0;
    let count = 0;
  
    if (str === '') {
        return 0;
    };
    
    for (let i = 0 ; i < str.length ; i++) {
        // if character is not empty and is a number,
        // increase count and sum
        if (str[i] !== ' ' && !isNaN(Number(str[i]))) {
            count++;
            sum = sum + Number(str[i]);
        }
    }
 
    return Math.round(sum/count);
}

let output = numberSearch('Hello6 ');
console.log(output); // 6 now, 6 / 1

output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 6 now, 17 / 3


推荐阅读