Coercion

ToBoolean

Falsy Values

All of JavaScript's values can be divided into two categories:

  1. values that will become false if coerced to boolean
  2. everything else (which will obviously become true)

the so-called "falsy" values list:

  • undefined
  • null
  • false
  • +0, -0, and NaN
  • ""

That's it. If a value is on that list, it's a "falsy" value, and it will coerce to false if you force a boolean coercion on it.

By logical conclusion, if a value is not on that list, it must be on another list, which we call the "truthy" values list. But JS doesn't really define a "truthy" list per se. It gives some examples, such as saying explicitly that all objects are truthy, but mostly the spec just implies: anything not explicitly on the falsy list is therefore truthy.

var a = "false";
var b = "0";
var c = "''";

var d = Boolean( a && b && c );

d;

Falsy Objects

Wait a minute, that section title even sounds contradictory. I literally just said the spec calls all objects truthy, right? There should be no such thing as a "falsy object."

What could that possibly even mean?

You might be tempted to think it means an object wrapper (see Chapter 3) around a falsy value (such as "", 0 or false). But don't fall into that trap.
**"falsy objects" are not just objects wrapped around falsy values, **

conclusion

![]
// false
!{}
// false
!function(){}
// false
!''
// true
Boolean('')
// false
!null
// true
!undefined
// true
!0
// true
'fasle' && '0' && "''"
// "''"

object自动转换成string的规则:

  1. 如果object所属类覆写了toString()方法,则调用该方法。如果toString()调用的返回结果为Primitive(string、number、boolean、undefined、null),则将该Primitive值转换成string后返回。

  2. 如果object所属类没有覆写toString()方法 – toString()调用的返回结果为”[object Object]“;或者覆写了toString()方法但该方法返回结果为对象。那么JS将调用object的valueOf()方法,如果valueOf()调用的返回结果为Primitive(string、number、boolean、undefined、null),则将该Primitive值转换成string后返回。

  3. 如果上述两点均无法满足,无法通过调用object的toString()方法或者valueOf()方法来获取Primitive值,那么JS将抛出TypeError错误。

object自动转换成number的规则:

  1. 调用object的valueOf()方法,如果得到的是Primitive值,则将该Primitive值转换成number后返回。

  2. 如果无法从valueOf()方法中获取Primitive值,那么调用object的toString()方法;如果toString()返回的是Primitive值,则将该Primitive值转换成number后返回。

  3. 如果上述两点均无法满足,那么JS将抛出TypeError错误。

可以看到,object自动转换成string和object自动转换成number的规则其实是一致的,不同之处在于toString()方法和valueOf()方法的调用次序。

var a = {
	valueOf: function() { return 42; },
	toString: function() { return 4; }
};

a + "";			// "42"

String( a );	// "4"

根据上述规则,可以很好的理解一些转换结果:

  1. 对于空数组,当将其转换成number时,得到的结果为0。这是因为首先会调用array的valueOf()方法,由于valueOf()返回的是数组对象本身,因此接下来JS会调用空数组的toString()方法;因为空数组toString()后返回结果为空字符串,因此最终会将空字符串转换成数字0后返回。

  2. 对于只有一个数字成员的数组来说,应用同样的规则转换成number,最后得到的结果就是该数字。

  3. 对于有多个数字成员的数组来说,由于无法将字符串转换成number,因此最后得到的结果为NaN。

原文地址:https://www.cnblogs.com/zlv2snote/p/10754969.html