javascript - 如何用 && 正确检查两个条件
问题描述
我想遍历一个数组并检查每个元素是一个数字还是一个可能变成数字的字符串(例如“42”)。如果可以“转换”,则该元素应存储在新数组中。
这是我的代码,我将所有转换后的元素推送到一个新数组中。注意:我还想计算有多少元素从字符串“转换”为数字,有多少没有。
function numberConverter(arr) {
var converted = []
var counterConverted = 0
var counterNotConverted = 0
for (var c of arr) {
if (typeof c == "string" && Number(c) == "number") {
counterConverted++;
parseInt(c, 10);
converted.push(c)
} else {
counterNotConverted++
}
}
if (counterConverted == 0) {
return "no need for conversion"
} else {
return counterConverted + " were converted to numbers: " + converted + "; " + counterNotConverted + " couldn't be converted"
}
}
我知道我的 if 条件
if(typeof c == "string" && Number(c) == "number")
在逻辑上存在缺陷,但我无法弥补原因。
感谢您的任何提示,请以初学者的方式进行解释。
解决方案
您可以测试是否可以将字符串转换为数字,如下所示:
val !== "" && Number.isNaN(Number(val)) === false
代码可以这样写:
function numberConverter(arr) {
var converted = [];
var notconverted = [];
arr.forEach(function(val) {
if (typeof val === "number") {
converted.push(val);
} else if (typeof val === "string" && val !== "" && Number.isNaN(Number(val)) === false) {
converted.push(Number(val));
} else {
notconverted.push(val);
}
});
console.log("converted", converted);
console.log("not converted", notconverted);
}
numberConverter([0, "1", "", "123-foo", undefined, null, true, [], {}]);
推荐阅读
- python - 通过首先读取镶木地板文件将新列附加到数据框
- c++ - 在 OpenGL ES 2.0 中显示意外的行
- python - 在 python 中使用 textblob 进行翻译的问题 - textblob.exceptions
- c++ - 在类外访问类的私有成员
- angular - 在响应类型类中改变返回的数据
- css - 使用 flexbox 的引导样式网格
- c - 在openmp中计算时间的正确方法
- regex - 是否可以改进此正则表达式以在 Excel 单元格中查找编号的文本行以避免错误匹配?
- reactjs - 在反应路由器中将/:id与一个不同的id分开的最佳方法是什么
- python - 绘制数学求和函数 (Alpine1)