Reading <Types & Grammar> - 2
Chapter 4: Coercion
Converting Values
Converting a value from one type to another is often called “type casting,” when done explicitly, and “coercion” when done implicitly (forced by the rules of how a value is used).
显式类型转换和隐式类型转换对应的英文。
The terms “explicit” and “implicit,” or “obvious” and “hidden side effect,” are relative.
If you know exactly what
a + ""
is doing and you’re intentionally doing that to coerce to astring
, you might feel the operation is sufficiently “explicit.” Conversely, if you’ve never seen theString(..)
function used forstring
coercion, its behavior might seem hidden enough as to feel “implicit” to you.
这段挺有意思,即隐式或显式是相对的,即一个人如果对某种方式进行的类型转换非常熟悉,那么这种方式对于他来说就是显示的,反之亦然。
当然这有一些诡辩的感觉,毕竟你写的代码不是只有你一个人看的,那么可以认为大多数人熟悉的类型转换方式为显式,否则为隐式比较合适。
Abstract Value Operations
The
JSON.stringify(..)
utility will automatically omitundefined
,function
, andsymbol
values when it comes across them. If such a value is found in anarray
, that value is replaced bynull
(so that the array position information isn’t altered). If found as a property of anobject
, that property will simply be excluded.Consider:
JSON.stringify( undefined ); // undefined JSON.stringify( function(){} ); // undefined JSON.stringify( [1,undefined,function(){},4] ); // "[1,null,null,4]" JSON.stringify( { a:2, b:function(){} } ); // "{"a":2}"
JSON.stringify(..)
使用注意事项1。此外,如果函数对象拥有toJSON
方法,则序列化时会使用这个方法的返回值,而不是undefined
或是被忽略了。(另一个角度,即toString
、toJSON
这类方法可以看作是这些JavaScript标准库提供的对应的hook,方便其他代码更好地适用于标准库方法。)