This time I will bring you a summary of JS implicit type conversion . What are the precautions for JS implicit type conversion? The following is a practical case, let’s 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
Data that will be converted to false
if(false) console.log(2333) if('') console.log(2333) if(null) console.log(2333) if(undefined) console.log(2333) if(NaN) console.log(2333)
Data that will be converted to true
if(true) console.log(2333) // 2333 if('test') console.log(2333) // 2333 if([]) console.log(2333) // 2333 if({}) console.log(2333) // 2333
All operations involved will be implicitly converted to string
Data that will be converted to an empty string
'str-' + '' // str- 'str-' + []
Data that will be converted to 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"
Data that will be converted to data type tag
'str-' + {} // "str-[object Object]" 'str-' + {a:1} // "str-[object Object]"
Participating in * operations will be implicitly converted to 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 it is 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 it 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 the empty string '' under the operator, and is converted to the number 0 under the * operator. But in the if statement, it turns true.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
JS click to cycle to switch to play pictures
JS implements multiple choice assessment system
js implements dynamic process progress display bar
The above is the detailed content of Summary of JS implicit type conversion. For more information, please follow other related articles on the PHP Chinese website!