各种型的 toString 方法合集

toString()

Object.prototype.toString()
Array.prototype.toString()
Boolean.prototype.toString()
RegExp.prototype.toString()
String.prototype.toString()
Number.prototype.toString()
Function.prototype.toString()
Date.prototype.toString()

Array,Boolean,RegExp,String,Number,Function,Date这些都是覆盖了 ObjecttoString 方法数组

Object.prototype.toString()

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

来自MDN的描述: 每一个对象都有一个toString()方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认状况下,toString()方法被每一个Object对象继承。若是此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中type是对象的类型
var obj = new Object()
obj.toString() // "[object Object]"

能够覆盖默认的 toString 方法

toString() 方法不能传入参数, 必需要返回一个字符串prototype

function Person(name, age) {
  this.name = name
  this.age = age
}
Person.prototype.toString = function() {
  return 'my name is ' + this.name + ', my age is ' + this.age
}
var fe = new Person('fe_feng', 23)
fe.toString() // "my name is fe_feng, my age is 23"

使用 toString() 检测对象类型

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

Boolean.prototype.toString()

返回指定的布尔对象的字符串形式
返回值为 "true" 或者 "false"
Boolean 对象覆盖了 Object 对象的 toString 方法
没有继承 Object.prototype.toString()
当一个 Boolean 对象做为文本值或进行字符串链接时, JS会自动调用其 toString 方法code

'1' + true  // "1true"

Array.prototype.toString()

返回一个表示指定的数组及其元素的字符串。
Array 对象覆盖了 ObjecttoString 方法
toString 方法链接数组并返回一个字符串,其中包含用逗号分隔的每一个数组元素对象

运用这个方法,能够处理数组扁平化, 不过有一些限制。继承

  • 当数组元素都是字符串时,扁平化处理很简单
function flatten(arr) {
    return arr.toString().split(',')
}
  • 当数组元素都是数字时,扁平化处理以下
function flatten(arr) {
  return arr.toString().split(',').map(item => +item)
}
  • 当数组元素不肯定时候,这个方法就不行了(返回的数组会改变原数组对象)

Number.prototype.toString()

返回指定 Number 对象的字符串表示形式ip

numObj.toString([radix]) 
// radix: 指定要用于数字到字符串的转换的基数(从2到36)。若是未指定 radix 参数,则默认值为 10。
// 若是 toString() 的 radix 参数不在 2 到 36 之间,将会抛出一个 RangeError。
栗子来源 MDN
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'
相关文章
相关标签/搜索