前言
Array、Boolean、Date、Number等對象都具有
toString()、toLocaleString()、valueOf()三個方法,那這三個方法有什么區別?
一、JS Array
1)舉例
var array = new Array("niu","li","na");
console.log(array.valueOf());
console.log(array.toString());
console.log(array.toLocaleString());
2)結果
3)總結
valueOf:返回數組本身
toString():把數組轉換為字符串,並返回結果,每一項以逗號分割。
toLocalString():把數組轉換為本地數組,並返回結果。
二、JS Boolean
1)舉例
var boolean = new Boolean();
console.log(boolean.valueOf());
console.log(boolean.toString());
2)結果
fasle,fasle
3)總結
valueOf:返回 Boolean 對象的原始值。
toString():根據原始布爾值或者 booleanObject 對象的值返回字符串 "true" 或 "false"。默認為"false"。
toLocalString():Boolean對象沒有toLocalString()方法。但是在Boolean對象上使用這個方法也不會報錯。
三、JS Date
1)舉例
var date = new Date();
console.log(date.valueOf());
console.log(date.toString());
console.log(date.toLocaleString());
2)結果
3)總結
valueOf:返回 Date 對象的原始值,以毫秒表示。
toString():把 Date 對象轉換為字符串,並返回結果。使用本地時間表示。
toLocalString():可根據本地時間把 Date 對象轉換為字符串,並返回結果,返回的字符串根據本地規則格式化。
四、JS Math
1)舉例
console.log(Math.PI.valueOf());
2)結果
3)總結
valueOf:返回 Math 對象的原始值。
五、JS Number
1)舉例
var num = new Number(1337);
console.log(num.valueOf());
console.log(num.toString());
console.log(num.toLocaleString());
2)結果
3)總結
valueOf:返回一個 Number 對象的基本數字值。
toString():把數字轉換為字符串,使用指定的基數。
toLocalString():把數字轉換為字符串,使用本地數字格式順序。
六、JS String
1)舉例
var string = new String("abc");
console.log(string.valueOf());
console.log(string.toString());
2)結果
abc
abc
3)總結
valueOf:返回某個字符串對象的原始值。
toString():返回字符串。
七、toString() VS toLocalString()
- toLocalString()是調用每個數組元素的 toLocaleString() 方法,然后使用
地區特定的分隔符把生成的字符串連接起來,形成一個字符串。 - toString()方法獲取的是String(傳統字符串),而toLocaleString()方法獲取
的是LocaleString(本地環境字符串)。 - 如果你開發的腳本在世界范圍都有人使用,那么將對象轉換成字符串時請使用
toString()方法來完成。 - LocaleString()會根據你機器的本地環境來返回字符串,它和toString()返回的
值在不同的本地環境下使用的符號會有微妙的變化。 - 所以使用toString()是保險的,返回唯一值的方法,它不會因為本地環境的改變而
發生變化。如果是為了返回時間類型的數據,推薦使用LocaleString()。若是在后台
處理字符串,請務必使用toString()。