JS -- + 号

212 阅读1分钟
  • 加号在遇到数字/undefined/null,只是做加法运算
1 + undefined  //NaN
1 + null       // 1

NaN + 任意数字,结果都为NaN
  • 加号遇到其他,则是连接字符串的作用
    • 遇到数组,数组转为字符串再连接
    • 遇到{}, 对象转为"[object Object]"再连接
1 + {}  // {}会转为"[object Object]", 结果为"1[object Object]"
1 + [] // "1"
1 + undefined + ''  //"NaN"
1 + undefined + 12  //NaN
1 + undefined + '12'  //"NaN12"
1 + [12]    // [12]数组转为字符串为"12", 结果为"112"
1 + [12,12] //"112,12"
undefined + ''  //"undefined"
null + ''   //"null"
false + ''  //"false"
{} + ''   //"[object Object]"
[] + ''  //""
tip:
Number() 当参数为数组时:会先把数组转为字符串
Number([12])   //12
Number([12, 13]) //NaN