[size=medium]When a non-null object is used in a Boolean context, it converts to true . When an object is used in a
string context, JavaScript calls the toString( ) method of the object and uses the string value returned
by that method. When an object is used in a numeric context, JavaScript first calls the valueOf( ) method
of the object. If this method returns a primitive value, that value is used. In most cases, however, the
valueOf( ) method returns the object itself. In this case, JavaScript first converts the object to a string
with the toString( ) method and then attempts to convert the string to a number.[/size]
string context, JavaScript calls the toString( ) method of the object and uses the string value returned
by that method. When an object is used in a numeric context, JavaScript first calls the valueOf( ) method
of the object. If this method returns a primitive value, that value is used. In most cases, however, the
valueOf( ) method returns the object itself. In this case, JavaScript first converts the object to a string
with the toString( ) method and then attempts to convert the string to a number.[/size]
本文详细介绍了JavaScript中对象在不同上下文中如何被转换为布尔值、字符串和数值。当对象用于布尔上下文时,非空对象转换为true;在字符串上下文中,通过调用对象的toString()方法来获取其字符串表示形式;而在数值上下文中,则先尝试调用valueOf()方法获取原始值,若该方法返回对象本身,则进一步使用toString()方法将其转换为字符串,并最终将该字符串转换为数值。
463

被折叠的 条评论
为什么被折叠?



