如何正确使用&&检查两个条件

时间:2019-08-29 11:47:48

标签: javascript casting numbers operators

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

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

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

最好的解决方案是对代码使用功能性方法,而不是命令性方法。

let arrayNumbers = ["Vadim", 99, {}, [], "100", "55AA", "AA55", Infinity, "false", true, null, -65.535, 2E1, "2E2"].filter( value => value !== null && value != Infinity && value !== '' && !isNaN(Number(value)) && !['boolean','array','object'].includes(typeof value)).map(value => +value);

console.log('Was Converted to Numbers:', arrayNumbers);

答案 2 :(得分:0)

您需要以typeofisNaN)的方式检查ESLint字符串和Number.isNaN(Number())

function numberConverter(arr) {
  const converted = [];
  let counterConverted = 0;

  for (let i = 0; i < arr.length; i += 1) {
    const str = arr[i];
    if (str && typeof str === 'string' && !Number.isNaN(Number(str))) {
      const number = parseInt(str, 10);
      converted.push(number);
      counterConverted += 1;
    }
  }
  const counterNotConverted = arr.length - converted.length;

  if (counterConverted === 0) {
    return 'No need for conversion.';
  }
  return `${counterConverted} were converted to numbers: ${converted.join(',')}; ${counterNotConverted} couldn't be converted`;
}

console.log(`'${numberConverter(['id', null, {}])}'`); // No need for conversion.
console.log(`'${numberConverter(['1', '-1', 'val'])}'`); // 2 were converted to numbers: [1,-1]; 1 couldn't be converted
console.log(`'${numberConverter(['1', '-1', '0', '1.5', 'val'])}'`); // 4 were converted to numbers: [1,-1,0,1]; 1 couldn't be converted