转字符串 toString()
Number.prototype.toString()
toString()
方法:返回指定 Number
对象的字符串表示形式。- 语法:
numObj.toString([radix])
- 如果未指定 radix 参数,则默认值为 10。
var count = 10;
console.log(count.toString());
console.log((17).toString());
console.log((17.2).toString());
var x = 6;
console.log(x.toString(2));
console.log((254).toString(16));
console.log((-10).toString(2));
console.log((-0xff).toString(2));
Array.prototype.toString()
toString()
方法:返回由数组中每个值的等效字符串拼接而成的一个由逗号分隔的字符串。
let colors = ['red','green','blue'];
console.log(colors.toString());
Object.prototype.toString()
toString()
方法:返回一个表示该对象的字符串。- 默认情况下,
toString()
方法被每个 Object
对象继承。 - 如果此方法在自定义对象中未被覆盖,
toString()
返回 “[object type]
”,其中 type
是对象的类型。
var o = new Object();
o.toString();
var toString = Object.prototype.toString;
toString.call(new Date);
toString.call(new String);
toString.call(Math);
toString.call(undefined);
toString.call(null);
Function.prototype.toString()
toString()
方法:返回一个表示当前函数源代码的字符串。
function sum(a, b) {
return a + b;
}
console.log(sum.toString());
console.log(Math.abs.toString());
返回本身 valueOf()
valueOf()
方法:用于返回指定对象的原始值,若对象没有原始值,则将返回对象本身。- 通常由JavaScript内部调用,而不是在代码中显式调用。
- 当遇到要预期的原始值的对象时,JavaScript会自动调用它。
var array = ["ABC", true, 12, -5];
console.log(array.valueOf() === array);
var date = new Date(2013, 7, 18, 23, 11, 59, 230);
console.log(date.valueOf());
var num = 15.26540;
console.log(num.valueOf());
var bool = true;
console.log(bool.valueOf() === bool);
var newBool = new Boolean(true);
console.log(newBool.valueOf() == newBool);
console.log(newBool.valueOf() === newBool);
function foo(){}
console.log( foo.valueOf() === foo );
var foo2 = new Function("x", "y", "return x + y;");
console.log( foo2.valueOf() );
var obj = {name: "张三", age: 18};
console.log( obj.valueOf() === obj );
var str = "http://www.xyz.com";
console.log( str.valueOf() === str );
var str2 = new String("http://www.xyz.com");
console.log( str2.valueOf() === str2 );