js的toString方法详解,可以实现获取随机字符串

            toString()方法

            1、返回一个数字对应的字符串

            2、返回一个表示该对象的字符串

            3、检测对象类型

                Object.prototype.toString()方法

                返回对象的类型字符串,可用来判断一个值的类型

                不能直接用toString()以防被对象重写

                用call方法


        const num = 123;
        console.log('第一:',num.toString());
        //第一: 123

        class Student {
            constructor(name,age){
                this.name = name;
                this.age = age;
            }
        }
        const p = new Student('tom', 11);
        console.log('第二:', p.toString())
        //第二: [object Object]

        class Person {
            constructor(name, age){
                this.name = name;
                this.age = age;
            }
            toString(){
                return '我的名字' + this.name
            }
        }
        const q = new Person('少林', 18);
        console.log('第三:重写后:',q.toString());
        //第三:重写后: 我的名字少林


        /**
         * 想通过toString()方法查看对象的类型
        */
        console.log('第三:原型:',Object.prototype.toString.call(q));
        //第三:原型: [object Object]

        /** call()方法也可以带参数
                    
            var person = {
            fullName: function(city, country) {
                return this.firstName + " " + this.lastName + "," + city + "," + country;
            }
            }
            var person1 = {
            firstName:"Bill",
            lastName: "Gates"
            }
            person.fullName.call(person1, "Seattle", "USA");

         */
         const mm = '123';
         console.log('第四:',Object.prototype.toString.call(mm));
         // -> 第四: [object String]

         console.log('第五:随机数:',Math.random().toString());
         //第五:随机数: 0.6868595385590079
         console.log('第五:二进制:',Math.random().toString(2));
         //第五:二进制: 0.0001111000110011101111100001111101011010011110111111
         console.log('第五:36进制:',Math.random().toString(36));
         //第五:36进制: 0.8c67vno1ll3
         console.log('第五:随机字符:',Math.random().toString(36).substr(2).length);
         //第五:随机字符: 11
         console.log('第五:参数为0:',Math.random().toString(0));
         //直接报错

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值