(1)to.string()不能转换null和undefined
console.log(null.toString());//typeError
console.log(undefined.toString());//typeErrorconsole.log(NaN.toString()=='NaN');//true
console.log(false.toString()=='false');//true
console.log([1,2].toString()=='1,2');//true
console.log({'a'}.toString());//syntaxError
(2)String()以构造函数的方式转换字符串,可以转换null和undefined
console.log(String(null)=='null');//trueconsole.log(String(undefined)=='undefined');//true
console.log(String(false)=='false');//true
console.log(String([1,2])=='1,2');//true
console.log(String({'1'})=='1');//syntaxError
注:两者都不能转换非空的Object对象
本文探讨了to.string()与String()两种方法在JavaScript中将不同数据类型转换为字符串时的行为差异。to.string()无法处理null、undefined及非空对象,而String()则可以转换null和undefined,但同样无法直接转换非空对象。
1496

被折叠的 条评论
为什么被折叠?



