转换为字符串的方法

2022-08-22  本文已影响0人  未路过

1. 1.如果+运算符左右两边有一个是字符串,那么另一边会自动转换成字符串类型进行拼接

Number(NaN Infinity 0) String Boolean undefined null

    console.log(123 + '');//123
    console.log(typeof (123 + ''))//string
    console.log( 0 + '')//0
    console.log(typeof (0 + ''))//string
    console.log(NaN + '')//NaN
    console.log(typeof (NaN + ''))//string
    console.log(Infinity + '')//Infinity
    console.log(typeof (Infinity + ''))//string

    console.log(true + '');//true
    console.log(typeof (true + ''))//string
    console.log(false + '');//false
    console.log(typeof(false + ''))//string

    console.log(undefined + '');//undefined
    console.log(typeof (undefined + ''))//string

    console.log(null + '');//null
    console.log(typeof (null + ''))//string

    console.log({name:"why", age: 18} + '')//[object Object]

2.调用String()函数


    console.log(String(123));//123
    console.log(typeof String(123));//string
    console.log(String(0));//0
    console.log(typeof String(0));//string
    console.log(String(NaN));//NaN
    console.log(typeof String(NaN));//string
    console.log(String(Infinity));//Infinity
    console.log(typeof String(Infinity));////string


    console.log(String(true))//true
    console.log(typeof String(true))//string
    console.log(String(false))//false
    console.log(typeof String(false))//string
    console.log(String(undefined))//undefined
    console.log(typeof String(undefined))//string
    console.log(String(null))//null
    console.log(typeof String(null))//string

3.调用toString()方法

toString()方法可以根据所传递的参数把数值转换为对应进制的数字字符串。参数范围为 2~36 之间的任意整数。
除了null和undefined之外,其他的数据类型(数值,布尔,字符串,对象)都有toString()方法,它返回响应值的字符串表现。
每一个对象都有一个toString()方法
他是Object原型上的一个方法。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

- toString() 是有返回值的,不会改变元数据
- null和undefined这两个值没有 toString()方法
- 如果调用他们的方法,就会报错

    var a = 32;
    console.log(a.toString(2));  //返回字符串100000
    console.log(a.toString(4));  //返回字符串200
    console.log(a.toString(16));  //返回字符串20
    console.log(a.toString(30));  //返回字符串12
    console.log(a.toString(32));  //返回字符串10

 

   console.log(NaN.toString());//'NaN'
   console.log(Infinity.toString());//'Infinity'
   console.log((0).toString());//'0'
   console.log((123).toString())//'123'
   console.log(true.toString())//"true"
   var foo = function() {
    console.log('foo')
   }
   console.log(foo.toString())
   /* function() {
    console.log('foo')
   } */

   console.log([1, 2, 3].toString())//1,2,3

   /* 对于对象,并且toString()方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中 type 是对象的类型。 */
   console.log({name:'why', age: 18}.toString())//[object Object]
上一篇下一篇

猜你喜欢

热点阅读