toLocaleString()方法和toString()方法

toLocaleString()方法和toString()方法

1、javascript中的toString()方法,主要用于Array、Boolean、Date、Error、Function、Number等对象

(1)、Array.toString():将数组转换成一个字符串,并且返回这个字符串

(2)、Boolean.toString():将布尔值转换为字符串。

(3)、Date.toString():将Date对象转换成一个字符串,采用本地时间。

(4)、Error.toString():将Error对象转换成字符串

描述:实现定义的字符串。ECMAScript标准除了规定该方法的返回值是字符串外,没有再做其他规定。尤其是,它不要求返回的字符传包含错误名和错误信息。

var e = new Error();
alert(e); //error
alert(typeof e.toString()); //string

(5)、Function.toString():把函数转换成字符串

描述:可以以一种与实现相关的方法将函数转换成字符串。在大多数的实现中,例如ie和firefox,它返回Function关键字、参数列表、函数体部分。

function add(a,b){
    var a,b,c;
     c = a + b;
     return c;
}
alert(add.toString());  
alert(typeof add.toString()); //string

(6)、Number.toString():将数字转换为字符串。用它的参数指定的基数或底数(底数范围为2-36)。如果省略参数,则使用基数10。当参数值为2时,返回二进制数。

var a = 34;
alert(a.toString()); //34
alert(a.toString(2)); //100010
alert(a.toString(8)); //42
alert(a.toString(16)); //22

2、javascript中的toLocaleString()方法,主要用于将数组 Number对象或Date对象转换为本地格式的字符串.

(1)、toLocaleString()是返回采用地方日期使用地方日期格式的规范的字符串。

var today = new Date();
alert(today); //Sat Jul 19 2008 23:27:14 GMT+0800
alert(today.toString()); //Sat Jul 19 2008 23:27:14 GMT+0800  本地时间
alert(today.toLocaleString()); //2008年7月19日 23:27:14  本地时间格式
alert(typeof today.toString()); //string
经验分享 程序员 微信小程序 职场和发展