首页 > 解决方案 > 如何用 && 正确检查两个条件

问题描述

我想遍历一个数组并检查每个元素是一个数字还是一个可能变成数字的字符串(例如“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") 在逻辑上存在缺陷,但我无法弥补原因。

感谢您的任何提示,请以初学者的方式进行解释。

标签: javascriptcastingnumbersoperators

解决方案


您可以测试是否可以将字符串转换为数字,如下所示:

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, [], {}]);


推荐阅读