除了 null 之外,幾乎所有 JavaScript 資料型別都具備 valueOf 與 toString 這兩個方法。它們負責解決「值運算」與「值顯示」兩件事。
function 函數名() { [native code] } 的字串。共同點:兩者在輸出物件時都會被自動呼叫。
不同點:兩者並存時,數值運算優先呼叫 valueOf,字串運算優先呼叫 toString。
var obj = {};
obj.valueOf = function() { return 10; };
obj.toString = function() { return "return value"; };
var result = obj + 1; // 等同 obj.valueOf() + 1
alert(result); // 11
alert(obj); // "return value"
function obj() { }
obj.prototype.toString = function(){ return 'dfsf'; };
obj.prototype.valueOf = function(){ return '3333'; };
var e = new obj();
var o = new obj();
alert(o); // "dfsf" —— 輸出時走 toString
alert(o + e); // "33333333" —— 加法時走 valueOf
兩者都無法用來取得 null 與 undefined 的值。
parseInt():顧名思義,把 String 轉為 int 型別。
String a = "123"; int b = Integer.parseInt(a); // b 等於 123
ValueOf():例如 Integer.valueOf() 是把 String 轉為 Integer 型別。注意 Integer 是參考的複雜型別,與表示數字的簡單型別 int 不同。
String a = "123"; Integer c = Integer.valueOf(a); int b = c.intValue(); // 需要時再轉為 int
toString():把參考型別轉為字串,與上面兩個方向相反。
Integer a = new Integer(123); String b = a.toString(); // "123"
整理成流程圖就是:
String --parseInt()/valueOf()--> int / Integer int --toString()-----------> String