Array、Boolean、Date、Number等對象都具備
toString()、toLocaleString()、valueOf()三個方法,那這三個方法有什麼區別?數組
1)舉例code
var array = new Array("niu","li","na"); console.log(array.valueOf()); console.log(array.toString()); console.log(array.toLocaleString());
2)結果
3)總結
valueOf:返回數組自己
toString():把數組轉換爲字符串,並返回結果,每一項以逗號分割。
toLocalString():把數組轉換爲本地數組,並返回結果。對象
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對象上使用這個方法也不會報錯。字符串
1)舉例string
var date = new Date(); console.log(date.valueOf()); console.log(date.toString()); console.log(date.toLocaleString());
2)結果
3)總結
valueOf:返回 Date 對象的原始值,以毫秒錶示。
toString():把 Date 對象轉換爲字符串,並返回結果。使用本地時間表示。
toLocalString():可根據本地時間把 Date 對象轉換爲字符串,並返回結果,返回的字符串根據本地規則格式化。console
1)舉例後臺
console.log(Math.PI.valueOf());
2)結果
3)總結
valueOf:返回 Math 對象的原始值。date
1)舉例方法
var num = new Number(1337); console.log(num.valueOf()); console.log(num.toString()); console.log(num.toLocaleString());
2)結果
3)總結
valueOf:返回一個 Number 對象的基本數字值。
toString():把數字轉換爲字符串,使用指定的基數。
toLocalString():把數字轉換爲字符串,使用本地數字格式順序。
1)舉例
var string = new String("abc"); console.log(string.valueOf()); console.log(string.toString());
2)結果
abc
abc
3)總結
valueOf:返回某個字符串對象的原始值。
toString():返回字符串。