javascript - 如何计算字符串中的数字?
问题描述
我的代码就是这样..我正在使用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
将是错误的,这里给出了一个很好的解释。
尝试使用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
推荐阅读
- node.js - Angular5:在本地将 Angular 应用程序部署到多个客户端
- wpf - 为 Mah:Tile 添加颜色动画
- uwp - 如何在 UWP 中为 Canvas.ZIndex = 5 的网格元素提供叠加层
- css - 当尝试在元素上使用 ms-clear 时它不起作用
- android - 如何通过单击按钮更改操作栏的标题?
- java - Selenium Appium Java Android Chrome 浏览器
- android - 在某些设备上拍照后应用程序关闭
- javascript - Socket IO空闲时随机发送数字
- hibernate - NHibernate hasOne 延迟加载
- c++ - 库被杀死时自动删除由库创建的文件