JavaScript Convert Object to String.png
1.Object
[JavaScript]
/*** object.toString() always return [object Object] ***/
var obj = {x: 1, y: 2};
obj.toString(); //=> "[object Object]"
obj = {};
obj.toString(); //=> "[object Object]
2.Array
[JavaScript]
/*** join each item with ',' ***/
var arr = [1, 2, 3];
arr.toString(); //=>"1,2,3"
arr = [1];
arr.toString(); //=>"1"
arr = [];
arr.toString(); //=>""
3.Function
[JavaScript]
/*** 函数的toString()方法,返回这个函数的定义表示 ***/
var func = function (x) { return x + 1 };
func.toString(); //=> "function (x) { return x + 1 }"
4.Date
[JavaScript]
/*** Date的toString()方法,返回一个可读的日期和时间字符串 ***/
var dt = new Date();
dt.toString(); //=> "Sat Apr 14 2018 18:15:38 GMT+0800 (中国标准时间)"
5.RegExp
[JavaScript]
/*** RegExp类的toString(),返回正则表达式直接量的字符串 ***/
var reg = /\d+/g;
reg.toString(); //=> "/\d+/g"
实例1
[JavaScript]
//对象obj转换为string类型
var obj = {x: 1, y: 2};
obj.toString(); //=> "[object Object]",原始值
------------------------------
//"+"运算符引发的类型转换
var obj = {x: 1, y: 2};
var num = 1 + obj;
console.log(num); //=> "1[object Object]"
num = "1" + obj;
console.log(num); //=> "1[object Object]"
------------------------------
//"=="运算符引发的类型转换
var obj = {x: 1, y: 2};
if("[object Object]" == obj){
console.log("Equal"); //=> "Equal"
}else{
console.log("Not Equal");
}
实例2
[JavaScript]
//数组arrj转换为string类型
var arr = [1, 2, 3];
arr.toString(); //=> "1,2,3",原始值
-------------------------------
arr = [9];
arr.toString(); //=> "9",原始值
-------------------------------
arr = [];
arr.toString(); //=> "",原始值
*******************************************
*** 实例 ***
*******************************************
//"+"运算符引发的类型转换
var arr = [1];
var num = 1 + arr;
console.log(num); //=> "11"
------------------------------
//"=="运算符引发的类型转换
var arr = [1];
if("1" == arr){
console.log("Equal"); //=> "Equal"
}else{
console.log("Not Equal");
}
if(1 == arr){
console.log("Equal"); //=> "Equal"
}else{
console.log("Not Equal");
}