javascript - 我如何计算数字并计算它?(我使用 isNaN())
问题描述
我的代码如下。我正在使用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]) // if it's a number
}
return Math.round(sum / strCount);
}
//debugger;
let output = numberSearch('Hello6 ');
console.log(output); // --> 1
output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1
我如何计算数字并计算它?
当我使用调试器时,总和是NaN
..我无法理解。
解决方案
问题是sum = sum + Number(str[i])
即使isNaN(Number(str[i])) === true
因为它在if
块之外,它也正在执行。您需要将它包装在else
块内,以便它仅在前一个条件为假时执行。
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
} else {
sum = sum + Number(str[i]) // if it's a number
}
}
return Math.round(sum / strCount);
}
//debugger;
let output = numberSearch('Hello6 ');
console.log(output); // --> 1
output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1
另一种方法是使用continue
声明。想一想continue
你对函数早期return
的思考方式,除了循环。
例如,您编写了:
function numberSearch(str) {
// . . .
if (str === "")
return 0
// . . .
}
这称为“提前返回”或“提前退出”。可以在循环中使用相同的技术:
for (let i = 0; i <= 10; i++) {
if (i % 3 === 0) // matches every multiple of 3 (3, 6, 9, etc.)
continue;
console.log(i)
}
这是您的代码,这次使用continue
.
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
continue
}
sum = sum + Number(str[i]) // if it's a number
}
return Math.round(sum / strCount);
}
//debugger;
let output = numberSearch('Hello6 ');
console.log(output); // --> 1
output = numberSearch('Hello6 9World 2,');
console.log(output); // --> 1
我建议您使用该if-else
版本,因为对于像这样简单的循环,使用continue
增加了一些不必要的金属开销。
话虽如此,如果循环中的逻辑增长(else
语句中的部分),您可能会发现如果您使用该continue
方法很容易阅读。最后,真正重要的是您个人认为更容易阅读的内容。
推荐阅读
- r - 允许用户单击并在视觉上移动绘图线的闪亮小部件,将这些更改反馈回修改后绘图的数字参数?
- karma-jasmine - 如何根据运行所需的时间使单元测试失败或通过?
- amazon-elastic-beanstalk - 我在 Infogix Data360 应用程序中收到错误 io.netty.channel.AbstractChannel$AbstractUnsafe.write(...)(Unknown Source)
- networking - Openstack Octavia 端口已关闭
- reactjs - 如何防止在 React 中未安装的组件中设置状态?
- assembly - 如何纯粹在 NASM 32 位汇编中对整数进行排序
- machine-learning - 如何获得每个 rfecv 分数的特征索引?
- java - 尝试全屏显示相机输出时无法查看完整图像
- angular - 如何下载 Base64 .docx 文件?
- java - 静态方法可以访问和修改java中的非静态字段吗?