简体   繁体   中英

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.

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.

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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