【问题标题】:Checking and converting some value to number using conditional operator使用条件运算符检查某些值并将其转换为数字
【发布时间】:2019-12-25 02:28:51
【问题描述】:

给定一个存储在变量“givenValue”中的字符串。如果都是数字,则将字符串转换为数字

(例如,'11' 到 11,'a1' 到 'a1')

并将其分配给变量“值”:

const value = givenValue - 0 === NaN ? givenValue : givenValue - 0;

但输出不是我预期的:

const givenValue = 'a1';
console.log(value); // NaN

const givenValue = '1';
console.log(value); // 1

似乎在检查“if”条件时重新分配了“givenValue”的值,或者条件检查不起作用。

【问题讨论】:

    标签: javascript numbers conditional-operator


    【解决方案1】:

    您可以使用isNaN 函数来检查是否是NaN:

    const givenValue = 'a1';
    console.log(isNaN(givenValue) ? givenValue : +givenValue);
    

    此外,如果您想在转换为数字之前检查某项是否为数字,您可以使用 isNaN 函数和 isFinite 函数:

    const givenValue = 'a1';
    
    const value = !isNaN(parseFloat(givenValue)) && isFinite(givenValue) 
                  ? givenValue : +givenValue;
    
    console.log(value);
    

    【讨论】:

      【解决方案2】:

      在许多情况下,字符串不是完全数字,但具有数字字符 may well return a number 而不是 NaN - 请参阅该链接以获取有关算法工作原理的完整说明。可以说,它有点复杂,不是你要找的。 (例如,您希望'123e456' 失败,但实际上这会给您Infinity。空格也将被允许。)(另外,=== NaN 检查将始终返回false,因为@987654327 @ 不等于任何东西)

      改为使用正则表达式来检查字符串是否只包含数字:

      const value = /^\d+$/.test(givenValue) ? Number(givenValue) : givenValue;
      

      如果您还想包括可能的小数,则添加可选的. 组,后跟数字:

      const value = /^\d+(?:\.\d+)?$/.test(givenValue) ? Number(givenValue) : givenValue;
      //                 ^^^^^^^^^^
      

      【讨论】:

      • 您能解释一下您的模式中的?: 部分吗?
      • 这是可选的. 组,后跟数字。例如,它将匹配1.123 的.123 部分 - 它匹配. 后跟\d+,数字
      • 因为我看到你有? 跟随群组(\.\d+),所以我想我们可以删除它?:。最后一个? 的意思是:组内的一切都可以是零次或一次,对吧?
      • 组开头的?: 使其无法捕获。仅当您需要捕获值时才应使用捕获组(仅用普通括号表示) - 否则,最好使用带有(?: 的非捕获组,以向阅读器和引擎指示匹配的子模式不需要保存或以后考虑。
      【解决方案3】:

      NaN 不等于自身。试试这样:givenValue - 0 !== givenValue - 0 ? givenValue : givenValue - 0。

      【讨论】:

        【解决方案4】:

        在 Javascript 中,NaN === NaN 总是错误的。

        所以你应该使用isNaN(givenValue - 0) 而不是givenValue - 0 === NaN

        console.log(NaN === NaN) // false
        console.log(NaN == NaN) // false
        console.log(isNaN(NaN)) // true
        
        const fixedFunc = (givenValue) => isNaN(givenValue - 0) ? givenValue : givenValue - 0;
        
        console.log(JSON.stringify({
          "fixedFunc('a1')": fixedFunc('a1'),
          "fixedFunc('1')": fixedFunc('1')
        }))

        【讨论】:

          【解决方案5】:

          仅适用于非零数字

          更简单的方法是使用const value = givenValue - 0 || givenValue;

          var givenValue = '1';
          var value = givenValue - 0 || givenValue;
          console.log(value);
          
          givenValue = 'a1';
          value = givenValue - 0 || givenValue;
          console.log(value);

          【讨论】:

            猜你喜欢
            • 2023-03-05
            • 2013-02-07
            • 2020-09-16
            • 2019-10-26
            • 1970-01-01
            • 1970-01-01
            • 2017-08-26
            • 2019-08-14
            • 1970-01-01
            相关资源
            最近更新 更多