通常存在四種狀況,JavaScript會對變量的數據類型進行轉換。javascript
* if中的條件會被自動轉爲Boolean類型 * 會被轉爲false的數據 * 會被轉爲true的數據 * 參與+運算都會被隱式的轉爲字符串 * 會被轉爲空字符串的數據 * 會被轉爲字符串的數據 * 會被轉爲數據類型標記的數據 * 參與*運算都會被隱式的轉爲數字 * 會被轉爲0的數據 * 會被轉爲1的數據 * 會被轉爲NaN的數據 * == 運算符 * 爲true的時候 * 爲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)
if(true) console.log(2333) // 2333 if('test') console.log(2333) // 2333 if([]) console.log(2333) // 2333 if({}) console.log(2333) // 2333
'str-' + '' // str- 'str-' + []
'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"
'str-' + {} // "str-[object Object]" 'str-' + {a:1} // "str-[object Object]"
2 * '' // 0 2 * [] // 0 2 * false // 0
2 * '1' // 2 2 * [1] // 2 2 * true // 2
2 * {} // NaN 2 * {a:1} // NaN
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
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
注:空數組[],在+運算符下是轉爲空字符串'',在*運算符下是轉爲數字0。但在if語句中,則轉爲true。前端
歡迎關注前端進階指南微信公衆號:java
另外我也創了一個對應的QQ羣:660112451,歡迎一塊兒交流。數組