1、两个操作数都是数值
let res = 1 + 1 // 2
复制代码
2、一个操作数为字符串,那么将另一个操作数转为字符串,最后将两个字符串拼接起来
// 另一个为字符串
'2' + '2' // "22"
// 另一个为数字类型
'2' + 2 // "22"
// 另一个为布尔类型
'2' + true // "2true"
// 另一个为null
'2' + null // "2null"
// 另一个为undefined
'2' + undefined // "2undefined"
// 另一个为对象类型
'2' + {a: 1} // "2[object Object]"
// 另一个为数组类型
'2' + [3, 4, 5] // "23, 4, 5"
// 另一个为Date类型
'2' + new Date() // "2Fri May 17 2019 11:18:30 GMT+0800 (中国标准时间)"
// 另一个为RegExp类型
'2' + new RegExp('str', "i") // "2/str/i"
// 另一个为Function类型
'2' + function fn() {console.log(333)} // "2function fn() {console.log(333)}"
// 另一个为Math类型
'2' + Math.floor(0.2) // "20"
// 另一个为window类型
'2' + window // "2[object Window]"
复制代码
3、操作数为null, undefined
null + null // 0
undefined + undefined //NaN
null + undefined // Nan
复制代码
总结
1、 Object.prototype.toString()
let o = {name: "tick"}
o.toString() // [object Object]
复制代码
2.、 Array.prototype.toString()
循环数组中的每一个元素,根据元素的类型不同则转换为不同形式的字符串
[1, {name: "x"}] + "" // "1,[object Object]"
[1, "2"].toString() // "1,2"
[1, new Date()].toString() // "1,Fri May 17 2019 15:11:43 GMT+0800 (中国标准时间)"
[1, [2, 2]].toString() // "1,2,2"
复制代码
以此类推