There are three conversions to study. Obviously numeric values will remain as they are.
This table summarizes the effects of converting values to numbers:
Value: | Numeric equivalent: |
---|---|
null | 0 |
Undefined value | NaN |
Empty string | 0 |
Numeric string | Numeric value of string |
Non-numeric string | NaN |
Boolean true | 1 |
Boolean false | 0 |
Object | Result of Object.valueOf(). |
Object lacking a valueOf() method. | Result of conversion of result from Object.toString() method. |
Object without toString() or valueOf() methods. | An error |
Array | No direct numeric equivalent |
Function | NaN |
Converting objects to numbers will first attempt to use the valueOf() method and then the toString() method, converting the resulting string to a number after that.
There is no proper numeric equivalent for an array. The ECMA standard does not address this either.
Some non-portable behavior has been implemented in the MSIE and Netscape browsers. In some cases, the array becomes NaN. In others, the first element is converted to a number. For some browsers this may only happen if the array is a single element long and the array is otherwise converted to NaN. Some browsers will take the length of the array and use that value.
You should test your target browsers to see what behavior persists if you intend to use this capability and not rely on any implicit array conversion facilities. It is probably safest to implement your own conversion method.
The array to number conversion is so inconsistently supported as to render it unusable in any cross browser implementation.
Prev | Home | Next |
Conversion to a Boolean | Up | Conversion to a string |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |