javascript中转换成字符串的三种方法

转换成string类型,有三种方式:变量.toString(); String('值'); 使用'+'拼接一个字符串;

每种方式都有使用的范围,我们可以通过下来代码得出以下结论:

在基本数据类型中,(1)只有number、boolean 类型调用toString()进行类型转换。

                                       undefined、null中没有toString()方法。

                                       toString()只能作用在变量身上,不能作用在常量上。

                              (2) undefiend与null可以通过String()转换称为字符串。

                                        常量可以使用String()转换称为字符串。

                              (3)所有的类型都可以通过拼接字符串转换成字符串。

在数组中,可以调用toString()方法与拼接字符串转换,但是不能使用String()。

贴下以下代码:

< script >
// 转换成string类型,三种方式:变量.toString(); String('值'); 使用'+'拼接一个字符串;
// number类型转string
// .toString()
var num = 123;
num = num.toString();
console.log( typeof num); //返回的是string;
// String()
var num2 = 50;
var str1 = String(num2);
console.log( typeof str1); //返回string
// 拼接字符串
var num3 = 60;
var str1s = num3 + '';
console.log(str1s);
console.log( typeof str1s); //返回string
// 常量:
// .toString()
// 123.toString(); //编辑器报错,说明没有这种写法
// String()
var str1 = String( 123);
console.log( typeof str1); //返回string


// boolean类型转string
// .toString()
var boo = false;
boo = boo.toString();
console.log( typeof boo); //返回的是string
// String()
var boo2 = true;
var str3 = String(boo2);
console.log( typeof str3); //返回string
// 拼接字符串
var boo3 = false;
var str3s = boo3 + '';
console.log(str3s);
console.log( typeof str3s); //返回string

// undefined转换成string
// .toString()
var und;
und = und.toString();
console.log(und);
console.log( typeof und); //报异常: Cannot read property 'toString' of undefined
// String()
var und2;
var str4 = String(und2);
console.log( typeof str4); //返回string
// 拼接字符串
var nud3;
var str4s = nud3 + '';
console.log(str4s);
console.log( typeof str4s); //返回string

// null转换成string
// .toString()
var nul = null;
nul = nul.toString();
console.log( typeof nul); //报异常:Cannot read property 'toString' of null
// String()
var nul2 = null;
var str5 = String(nul2);
console.log( typeof str5); //返回string
// 拼接字符串
var nul3;
var str5s = nul3 + '';
console.log(str5s);
console.log( typeof str5s); //返回string


// 复杂数据类型转字符串
// 数组调用toString();
var arr = [ 'hello', 'world'];
arr = arr.toString();
console.log(arr); //输出结果为“hello,world”;
console.log( typeof arr); //返回的是string
// 数组调用String();
var ars = [ 'jack', 'rose'];
ars = toString(ars);
console.log(ars); //输出结果是[object Undefined]
console.log( typeof ars); //返回的是string
// 拼接字符串
var arr = [ 'hello', 'world'];
arr = arr+ '';
console.log(arr); //输出结果为“hello,world”;
console.log( typeof arr); //返回的是string
< / script >




             


猜你喜欢

转载自blog.csdn.net/yellowmushroom/article/details/80252513