简体   繁体   中英

JavaScript Coercion for Strings to Logical Operators

I can understand that JavaScript will convert the one data type to another data type to match the data types automatically. But I don't understand the following results. Please explain the same for better understanding.

console.log("32" > "4") //This result is showing false. when converting the number it must be true. But, why its showing as false?
console.log("32" < "4") //This result is showing true. Why?
console.log("32" > "14") // Its showing true. How?

When javascript compares 2 strings, it compares the placement of the characters of the strings in a series, which for numbers is "0123456789".

The reason ("32" < "4" === true) is because 4 comes later than 3 in the series, that is, 4 is greater than 3 (JS always starts comparing with the first character). Javascript will only move on to the second character when the first character is equal in both strings. It performs the same operation and returns true, false or moves onto the next character. This is why:

"4" > "39" === true

"32" > "31" === true

"30" > "3" === true

And for your last example, I get the value of "32" < "14" as false.

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