The following editor will bring you a summary of the four situations where JavaScript implicit type conversion exists (a must-read article). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
Generally there are four situations. JavaScript will convert the data type of the variable.
Directory
* if中的条件会被自动转为Boolean类型 * 会被转为false的数据 * 会被转为true的数据 * 参与+运算都会被隐式的转为字符串 * 会被转为空字符串的数据 * 会被转为字符串的数据 * 会被转为数据类型标记的数据 * 参与*运算都会被隐式的转为数字 * 会被转为0的数据 * 会被转为1的数据 * 会被转为NaN的数据 * == 运算符 * 为true的时候 * 为false的时候
The conditions in if will be automatically converted to Boolean type
will be converted to False data
if(false) console.log(2333) if('') console.log(2333) if(null) console.log(2333) if(undefined) console.log(2333) if(NaN) console.log(2333)
will be converted into true data
if(true) console.log(2333) // 2333 if('test') console.log(2333) // 2333 if([]) console.log(2333) // 2333 if({}) console.log(2333) // 2333
will be implicitly converted into a string if it participates in the + operation
The data that will be converted into an empty string
'str-' + '' // str- 'str-' + []
The data that will be converted into a string
'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"
Will be converted into data marked with data type
'str-' + {} // "str-[object Object]" 'str-' + {a:1} // "str-[object Object]"
Will be implicitly converted into numbers when participating in * operation
will be Data converted to 0
2 * '' // 0 2 * [] // 0 2 * false // 0
will be converted to data of 1
2 * '1' // 2 2 * [1] // 2 2 * true // 2
will be converted to NaN data
2 * {} // NaN 2 * {a:1} // NaN
== Operator
is true when
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
is 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: The empty array [] is converted to an empty string '' under the + operator, and is converted to the number 0 under the * operator. But in the if statement, it turns true.
The above is the detailed content of Summarize the four situations of JavaScript implicit type conversion. For more information, please follow other related articles on the PHP Chinese website!