// Number + Number -> 数字相加 1 + 2 // 3 // Boolean + Number -> 数字相加 true + 1 // 2 // Boolean + Boolean -> 数字相加 false + false // 0 // Number + String -> 字符串连接 5 + "foo" // "5foo" // String + Boolean -> 字符串连接 "foo" + false // "foofalse" // String + String -> 字符串连接 "foo" + "bar" // "foobar" // String + null、String + undefined -> 字符串连接 null + '1' // null1 undefined + '1' // undefined1 // Number + null、Number + undefined -> 数字相加 null + 1 // 1 undefined + 1 // NaN (undefined转为数字是NaN)
1、数字相加:数字 + 数字、数字 + 布尔、布尔 + 布尔
布尔转数字
2、字符串连接:
一方是字符串的时候,另一方如果不是字符串,需要执行toPrimitive()操作,注意不是toString()
'abc' + 123; // 'abc123' 'abc' + true; // 'abctrue' 'abc' + []; // 'abc' 'abc' + {}; // 'abc[object Object]' // 注意不是toString() Object.defineProperty(Array.prototype,Symbol.toPrimitive,{ value(){ return '[]'; } }); [].toString(); // '' 'abc' + []; // 'abc[]' // 例2 Object.prototype.valueOf = function(){ return '{???}' }; console.log('abc' + {}); // 'abc{???}'
==运算符,即抽象比较,只想记录一点:
与+运算符不同的是,如果字符串与数字比较,则会把字符串转为数字
当然了,比较结果是可以被 Symbol.toPrimitive 修改的