使用条件运算符检查某些值并将其转换为数字

Checking and converting some value to number using conditional operator

给定一个存储在变量 'givenValue' 中的字符串。如果全是数字,把字符串转成数字

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

并将其分配给变量 'value':

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

但是输出不是我所期望的:

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

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

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

在许多情况下,不完全是数字但具有数字字符 may well return a number 而不是 NaN 的字符串 - 请参阅 link 以了解该算法如何工作的完整描述。可以说,它有点复杂,并不是您要找的。 (例如,您希望 '123e456' 失败,但实际上会给您 Infinity 代替。空格也将被允许。)(另外,=== NaN 检查将始终 return false, 因为 NaN 不等于任何东西)

相反,使用正则表达式检查字符串是否仅包含数字:

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

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

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

NaN 不等于自己。像这样尝试:givenValue - 0 !== givenValue - 0 ? givenValue : givenValue - 0.

您可以使用 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);

仅适用于非零数字

更简单的方法是使用 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);

在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')
}))