There are generally four situations, and JavaScript will convert the data types of variables.
Table of contents
* ifThe conditions in theBooleantype * Will be converted tofalseData of * Will be converted totrueData of * participate+All operations are implicitly converted to strings * Will be converted to空字符串Data of * Will be converted to字符串Data of * Will be converted to数据type标记Data of * participate*All operations are implicitly converted to numbers * Will be converted to0Data of * Will be converted to1Data of * Will be converted toNaNData of * == Operators * fortrueWhen * forfalseWhen
If the condition will be automatically converted to Boolean type
Data that will be converted to false
if(false) (2333) if('') (2333) if(null) (2333) if(undefined) (2333) if(NaN) (2333)
Data that will be converted to true
if(true) (2333) // 2333 if('test') (2333) // 2333 if([]) (2333) // 2333 if({}) (2333) // 2333
Participation + operation will be implicitly converted into strings
Data that will be converted to empty strings
'str-' + '' // str- 'str-' + []
Data that will be converted to strings
'str-' + '1' // "str-1" 'str-' + 1 // "str-1" 'str-' + false // "str-false" 'str-' + true // "str-true" 'str-' + null // "str-null" 'str-' + undefined // "str-undefined" 'str-' + NaN // "str-NaN"
Data that will be converted to data type tags
'str-' + {} // "str-[object Object]" 'str-' + {a:1} // "str-[object Object]"
Participating in * operations will be implicitly converted into numbers
Data that will be converted to 0
2 * '' // 0 2 * [] // 0 2 * false // 0
Data that will be converted to 1
2 * '1' // 2 2 * [1] // 2 2 * true // 2
Data that will be converted to NaN
2 * {} // NaN 2 * {a:1} // NaN
== operator
When true
0 == false // true 0 == '' // true 0 == '0' // true 0 == [] // true 0 == [0] // true 1 == true // true 1 == '1' // true 1 == [1] // true [1] == true // true [] == false // true
When false
0 == {} // false 0 == null // false 0 == undefined // false 0 == NaN // false 1 == {} // false 1 == null // false 1 == undefined // false 1 == NaN // false [] == [] // false [1] == [1] // false [1] == {} // false [1] == {a:1} // false [1] == false // false [1] == null // false [1] == undefined // false [1] == NaN // false {} == {} // false {a:1} == {a:1} // false
Note:Empty array[], converted to an empty string under the + operator, and converted to a number 0 under the * operator. But in the if statement, it turns to true.
The above summary of the four situations of implicit type conversion in JavaScript (must-read) is all the content I share with you. I hope you can give you a reference and I hope you can support me more.