JavaScript 中的显式类型转换和类型

Explicit Type Conversion and typeof in JavaScript

本文关键字:类型转换 类型 JavaScript      更新时间:2023-09-26
    var x = +"5";    // 5
    alert("string to number explicitly: "+typeof x); //  number

现在考虑一下:

当我们将字符串转换为数字时,如果字符串只是一个数字,则结果是字符串数值;所有其他字符串变为 NaN

var y = +"foo";  //NaN
alert(typeof y); // Why this results in number?

typeof NaN是作为"number",这是预期行为。更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

将变量转换为数字的最短形式。 +anything正在尝试将anything转换为数字。

由于"foo"是一个字符串而不是一个有效的数字,因此它返回NaN