隐式转换 vs 显式转换
Type coercion vs Type conversion
一句话:转换(conversion / casting)是你主动写的,强制转换(coercion)是引擎背着你干的。
| 谁发起 | 例子 | |
|---|---|---|
| 显式(conversion) | 你 | Number("42")、String(42)、Boolean(0)、parseInt("42px") |
| 隐式(coercion) | 引擎 | "5" * 2、1 + "1"、if (arr.length)、[] == false |
隐式转换的两条核心规则(记住这两条, 大部分怪题就能推出来):
+只要有一边是字符串,就变成拼接; 其他算术运算符(-、*、/)一律转成数字。 所以1 + "1" === "11"而"3" - 1 === 2。- 对象参与运算时先
valueOf()再toString()。 数组的toString()是元素 join 逗号, 所以[] + []得到空字符串,[] + {}得到"[object Object]"。
六个假值背下来(其余全是真):false、0、""、null、undefined、NaN。
注意 [] 和 {} 都是真值—— 所以判断数组空不空要看 arr.length。
会追问:「parseInt 和 Number 什么区别?」——parseInt("42px") 得 42(从头读到读不动为止),Number("42px") 得 NaN(整体不合法就失败)。 所以校验用户输入该用 Number,parseInt 会把脏数据悄悄放过去。
In one line: conversion (casting) is what you write on purpose; coercion is the engine doing it behind your back.
| Who starts it | Examples | |
|---|---|---|
| Explicit (conversion) | You | Number("42"), String(42), Boolean(0), parseInt("42px") |
| Implicit (coercion) | The engine | "5" * 2, 1 + "1", if (arr.length), [] == false |
Two rules cover almost all coercion — hold on to these and you can derive most of the trick questions:
+becomes concatenation the moment one side is a string; every other arithmetic operator (-,*,/) converts to number. Hence1 + "1" === "11"but"3" - 1 === 2.- An object in an operation goes through
valueOf()first, thentoString(). An array’stoString()joins its elements with commas, so[] + []gives an empty string and[] + {}gives"[object Object]".
Memorise the six falsy values (everything else is truthy): false, 0, "", null, undefined, NaN.
Watch out — [] and {} are both truthy, so check arr.length to tell whether an array is empty.
Follow-up: “What is the difference between parseInt and Number?” — parseInt("42px") gives 42 (it reads from the front until it cannot go on), while Number("42px") gives NaN (the whole string has to be valid). So validate user input with Number; parseInt waves dirty data straight through.