原始类型强转

<script>
    /***
        1.如果值有toString()方法,则调用toString()并返回结果
        2.如果值是null,则返回"null"
        3.如果值是undefined,则返回"undefined"
    **/
    cosole.log(String(true));//"true"
    
    cosole.log(String(false));//"false"

    cosole.log(String(10));//"10"

    cosole.log(String(null));//"null"

    cosole.log(String(undefined));//"undefined"
</script>

 这里Number类型,Boolean类型,String类型都有本身的toString()和valueOf()方法。

js字符串强转

js字符串强转

String原型链太长了,就不截图了

对象类型强转

先调用对象的toString()方法,如果返回值是原始类型(string,number,boolean,undefined,null),则String(toString()返回值),如果返回值是Object类型,则会调用对象的valueOf()方法,如果valueOf()返回值是原始类型,则String(valueOf()返回值),如果valueOf()方法返回值是Object类型,则强转失败,报错

var obj = {
    age:20,
    name:"pmx",
    valueOf:function(){
        console.log('value of');
        return "hello"
    },
    toString:function(){
        console.log("to string");
        return {}
    }
}

js字符串强转

toString()返回对象,则调用obj的valueOf()方法,结果是String("hello"),最终返回"hello";

 

var obj = {
    age:20,
    name:"pmx",
    valueOf:function(){
        console.log('value of');
        return {
            toString(){
                return 'world'
            },
            valueOf(){
                return 10;
            }
        }
    },
    toString:function(){
        console.log("to string");
        return {}
    }
}

js字符串强转

 

相关文章:

  • 2022-12-23
  • 2021-12-20
  • 2022-02-12
  • 2022-12-23
  • 2021-11-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-07
  • 2021-10-06
  • 2021-12-06
  • 2021-12-20
相关资源
相似解决方案