有两种方法:

1.对于boolean, number, string类型,可调用toString()方法

2.用String(var)方法

其中,第二种方法使用范围更广,可将没有toString()方法的undefined和null类型强制转换成字符串。

// 转换成字符串
// boolean转换成string
var foo = true;
console.log(`foo.toString(): ${foo.toString()}`); // foo.toString(): true
var foo = false;
console.log(`foo.toString(): ${foo.toString()}`); // foo.toString(): false
// number转换成string
var foo = 100;
console.log(`foo.toString(): ${foo.toString()}`); // foo.toString(): 100
var foo = 023;
console.log(`foo.toString(): ${foo.toString()}`); // foo.toString(): 19
var foo = 0x1F;
console.log(`foo.toString(): ${foo.toString()}`); // foo.toString(): 31
// Number.NaN
console.log(`Number.NaN.toString(): ${Number.NaN.toString()}`); // Number.NaN.toString(): NaN
// undefined转换成string
console.log(`String(undefined): ${String(undefined)}`); // String(undefined): undefined
var fooBar;
// undefined没有toString()方法
// console.log(fooBar.toString()); // Uncaught TypeError: Cannot read property 'toString' of undefined
// null转换成string
console.log(`String(null): ${String(null)}`); // String(null): null
var foooBar = null;
// null没有toString()方法
// console.log(foooBar.toString()); // Uncaught TypeError: Cannot read property 'toString' of null // 其他
// console.log(`foo.toSource(): ${foo.toSource()}`); // Uncaught TypeError: foo.toSource is not a function
console.log(`foo.valueOf(): ${foo.valueOf()}`); // foo.valueOf(): false
console.log(`foo.constructor: ${foo.constructor}`); // foo.constructor: function Boolean() { [native code] }
var foo = new Boolean(false);
// console.log(`foo.toSource(): ${foo.toSource()}`); // Uncaught TypeError: foo.toSource is not a function
console.log(`foo.valueOf(): ${foo.valueOf()}`); // foo.valueOf(): false
console.log(`foo.constructor: ${foo.constructor}`); // foo.constructor: function Boolean() { [native code] }
05-02 07:06