DrillLab
第 17 / 105 道17 / 105 · #279 / #386

隐式转换 vs 显式转换

Type coercion vs Type conversion

先自己答,再往下看Answer it yourself first

一句话:转换(conversion / casting)是你主动写的强制转换(coercion)是引擎背着你干的

谁发起例子
显式(conversion)Number("42")String(42)Boolean(0)parseInt("42px")
隐式(coercion)引擎"5" * 21 + "1"if (arr.length)[] == false

隐式转换的两条核心规则(记住这两条, 大部分怪题就能推出来):

  • + 只要有一边是字符串,就变成拼接; 其他算术运算符(-*/)一律转成数字。 所以 1 + "1" === "11""3" - 1 === 2
  • 对象参与运算时先 valueOf()toString()。 数组的 toString() 是元素 join 逗号, 所以 [] + [] 得到空字符串,[] + {} 得到"[object Object]"

六个假值背下来(其余全是真):false0""nullundefinedNaN
注意 []{} 都是真值—— 所以判断数组空不空要看 arr.length

会追问:parseIntNumber 什么区别?」——parseInt("42px")42(从头读到读不动为止),Number("42px")NaN(整体不合法就失败)。 所以校验用户输入该用 NumberparseInt 会把脏数据悄悄放过去。

In one line: conversion (casting) is what you write on purpose; coercion is the engine doing it behind your back.

Who starts itExamples
Explicit (conversion)YouNumber("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. Hence 1 + "1" === "11" but "3" - 1 === 2.
  • An object in an operation goes through valueOf() first, then toString(). An array’s toString() 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.

JavaScript隐式转换速查Coercion quick reference示意Illustrative
11 + "1" // "11" + 有字符串 -> 拼接
2"3" - 1 // 2 - 一律转数字
3"3" * "4" // 12
41 + true // 2 true -> 1
51 + null // 1 null -> 0
61 + undefined // NaN undefined -> NaN
7
8[] + [] // "" 两个空数组 toString 都是 ""
9[] + {} // "[object Object]"
10[1,2] + [3] // "1,23" join 逗号再拼
11
12Number("42px") // NaN 整体不合法
13parseInt("42px") // 42 读到读不动为止
14Number("") // 0 ← 注意,空字符串转数字是 0
15Number(" ") // 0 ← 空白也是 0,校验输入要小心
11 + "1" // "11" + with a string means concatenate
2"3" - 1 // 2 - always converts to number
3"3" * "4" // 12
41 + true // 2 true -> 1
51 + null // 1 null -> 0
61 + undefined // NaN undefined -> NaN
7
8[] + [] // "" toString of an empty array is ""
9[] + {} // "[object Object]"
10[1,2] + [3] // "1,23" join with commas, then concatenate
11
12Number("42px") // NaN the whole string has to be valid
13parseInt("42px") // 42 reads until it cannot read further
14Number("") // 0 ← note: an empty string converts to 0
15Number(" ") // 0 ← whitespace is 0 too, so validate input carefully
面试不会让你背全表,但会给两三个式子让你推。掌握「+ 看字符串、其他看数字」和「六个假值」就够推。An interview will not ask you to recite the whole table, but it will give you two or three expressions to work out. Remember that + looks for a string while every other operator converts to number, plus the six falsy values, and that is enough.