【问题标题】:How can I calculate the number within a string? [duplicate]如何计算字符串中的数字? [复制]
【发布时间】:2021-05-19 14:58:52
【问题描述】:

我的代码是这样的.. 我正在使用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' 我不能好好对待..我不能很好地理解..

【问题讨论】:

  • NaN !== NaN 将评估为true,因为“NaN”不等于任何值,包括它自己。您需要使用isNaN() 来检查给定值是否为 NaN。

标签: javascript


【解决方案1】:

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

NaN === NaN

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

尝试使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-20
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2012-11-30
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多