js字符串强转

 原始类型强转

<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()方法。

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 {}
    }
}

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 {}
    }
}

猜你喜欢

转载自www.cnblogs.com/bibiafa/p/9376749.html