JS基本——数据类型推断typeof、instanceof、Object.prototype.toString

  1. typeof用在基础数据范例和函数时,返回其对应范例的形貌,关于援用范例都返回为object.
  2. instanceof没法推断基础数据范例,关于援用范例数据,返回其其对应范例。
  3. Object.prototype.toString不管基础数据范例照样援用范例返回其对应范例。

对应测试效果以下:

typeof testinstanceofObject.prototype.toString.call(test)
var test = ‘xuriliang’;stringtest instanceof String //false[object String]
var test = 27;numbertest instanceof Number //false[object Number]
var test = true;booleantest instanceof Boolean //false[object Boolean]
var test = [1,2,3];objecttest instanceof Array //true[object Array]
test instanceof Object //true
var test = null;objecttest instanceof Object //false[object Null]
var test = undefined;undefinedtest instanceof Object //false[object Undefined]
var test = new String(‘xuriliang’)objecttest instanceof String //true[object String]
test instanceof Object //true
var test = new Number(27)objecttest instanceof Number //true[object Number]
test instanceof Object //true
var test = new Boolean(true)objecttest instanceof Boolean //true[object Boolean]
test instanceof Object //true
var test = new Array(1,2,3)objecttest instanceof Array //true[object Array]
test instanceof Object //true
var test = function(){}functiontest instanceof Function //true[object Function]
test instanceof Object //true
var test = /d/objecttest instanceof RegExp //true[object RegExp]
test instanceof Object //true
    原文作者:xuriliang
    原文地址: https://segmentfault.com/a/1190000018340166
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞