简体   繁体   English

哪一个是正确的? 警报((+“ 123”))警报(+“ 123”)警报(+(“ 123”))

[英]which one is correct? alert((+“123”)) alert(+“123”) alert(+(“123”))

I'm trying to convert a string to a float. 我正在尝试将字符串转换为浮点数。 I know that parseFloat() can do that, but I've also found the syntax below, but without much reference. 我知道parseFloat()可以做到这一点,但是我也找到了下面的语法,但是没有太多参考。

What is the correct syntax, because they all seem to work. 正确的语法是什么,因为它们似乎都可以工作。 And where can I learn more about it? 在哪里可以了解更多信息? I don't know how to Google it, because I don't know what it's named. 我不知道如何使用Google,因为我不知道它的名字。

// syntax 1
alert((+"123"));    // 123
alert((+"x123"));   // NaN
alert((+"123x"));   // NaN
alert((+"123   ")); // 123
alert((+"   123")); // 123
alert((+"12 3"));   // NaN

// syntax 2
alert(+"123");      // 123
alert(+"x123");     // NaN
alert(+"123x");     // NaN
alert(+"123   ");   // 123
alert(+"   123");   // 123
alert(+"12 3");     // NaN

// syntax 3
alert(+("123"));    // 123
alert(+("x123"));   // NaN
alert(+("123x"));   // NaN
alert(+("123   ")); // 123
alert(+("   123")); // 123
alert(+("12 3"));   // NaN

它们在语法上都是正确的...但是示例1和3具有多余的括号。

This is called implicit conversion. 这称为隐式转换。 Since you used a mathematical operator (+), it tries to convert the string to a numeric value which is needed for mathematical operations. 由于您使用了数学运算符(+),因此它将尝试将字符串转换为数学运算所需的数字值。 What you are asking here is give me the positive value of the following string. 您在这里要问的是给我以下字符串的正值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM