<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
//toString 和valueOf方法属性Object对象方法,因此所有对象都有该方法 null undefined 除外
//valueOf valueOf()函数返回指定对象的原始值。
//调用alert 方法会自动调用toString 方法
var a = false;
var atos = a.toString(); // 默认先执行new Boolean(a);将布尔类型转为的字符串类型
console.log(a, atos, typeof atos); //false “false" "string"
//console.log(null.toString())// 报错
//console.log(undefined.toString())//报错
var number = 100;
console.log(number.toString(2));
var str = String(null);
console.log(str, typeof str); //null string
var str2 = String(undefined);
console.log(str2, typeof str2); //undefined string
new String(null); //??
var arr = [1, 4, 'a', true];
console.log(arr.toString(), arr.valueOf());
var date1 = new Date();
console.log(date1.toString());
var err = new Error("我错了");
console.log(err, "wrong", err.toString());
//https://www.cnblogs.com/fybsp58/p/5683206.html
var fn = new Function();
console.log(fn.toString());
var num = 1024;
// 二进制
console.log(num.toString(2)); //转为二进制
var obj = {
name: 'Tom',
age: 29
};
console.log(obj.toString()) //[object Object]
//http://www.365mini.com/page/javascript-valueof.htm
console.log(arr.toString().valueOf()) // 和 arr.toString();方法一样的结果
console.log(typeof arr.valueOf()); //'object';
var ssttrr = new String("sss");
console.log(typeof ssttrr.valueOf()) //'string'
var colors = ["red", "blue", "green"]; // 创建一个包含3 个字符串的数组
//alert(colors.toString()); // red,blue,green
//alert(colors.valueOf()); // red,blue,green alert自动调用了toString方法
console.error(Array.isArray(arr.valueOf()));
var arr = [1, 2, 3];
arr.toString = function() {
alert("你调用了toString函数");
}
alert(arr.valueOf());
var strrr = '123';
console.error(typeof strrr.valueOf()); //'string'
//toString 和 new toString 区别https://www.cnblogs.com/chianquan/p/6075925.html
var str0 = 'str1';
var str1 = String("str1");
var str2 = new String("str2");
console.log(str1, typeof str1,str0===str1); //'string' true
console.log(str2, typeof str2, str2.toString()) //'object'类型
var Fun1 = function() {
return String('str1');
};
var Fun2 = function() {
return new String('str1');
};
console.log('Fun1 output:', new Fun1()); //Fun1 output: {}
console.log('Fun2 output:', new Fun2()); //Fun2 output: [String: 'str1']
//函数加new和不加new的区别https://zhidao.baidu.com/question/361146175916081012.html
function Call(){
this.x = 12;
this.y = 45;
return this.x+this.y;
}
console.log(new Call());//Call {x: 12, y: 45}
console.log(Call())// 57
</script>
</body>
</html>
js 中toString,valueOf(),new String(),String()以及new 函数(),和不new的区别
最新推荐文章于 2022-10-08 13:54:54 发布