js中toString方法

一、把数字转换为字符串

var count = 10;

console.log(count.toString());    // 输出 '10'
console.log((17).toString());     // 输出 '17'
console.log((17.2).toString());   // 输出 '17.2'

二、返回该数字对应进制的字符串

var x = 6;

console.log(x.toString(2));       // 输出 '110'
console.log((254).toString(16));  // 输出 'fe'

console.log((-10).toString(2));   // 输出 '-1010'
console.log((-0xff).toString(2)); // 输出 '-11111111'

三、检测对象的类型

第一种

Object.prototype.toString.call(arr)==="[object Array]"

第二种
每一个对象都有一个 toString()方法。 默认的情况下,toString()方法被每一个对象继承。如果toString没有被定义的对象覆盖。toString返回 ‘[object type]’ 其中type是对象的类型,type的值可以是Object

class Person{
    
    
  constructor(name,age){
    
    
    this.name=name
    this.age=age
  }
}
let zs=new Person('张三',18)
console.log( zs.toString() ) // [object Object]

https://www.runoob.com/jsref/jsref-tostring-number.html
https://www.jb51.net/article/233178.htm

猜你喜欢

转载自blog.csdn.net/weixin_46048542/article/details/129740685