01.javascript之数据类型


1.数据类型

JavaScript一共有六种数据类型。(ES6新增了第七种Symbol类型的值)

  • 数值(Number)
  • 字符串(String)
  • 布尔值(boolean)
  • undefined
  • null
  • 对象(object)

2.数据类型判断

JavaScript有三种方法,可以判断一个值的类型

  • typeof运算符
  • instanceof运算符
  • Object.prototype.toString()方法

typeof运算符

typeof运算符可以返回一个值的数据类型。
数值、字符串、布尔值分别返回numberstringboolean

typeof 123  //"number"
typeof 'hello'  //"string"
typeof true  //"boolean"

函数返回function

function f(){} 
typeof f  //"function"

undefined返回undefined

typeof undefined  // "undefined"

对象返回object

typeof {} // "object"
typeof [] // "object"

null返回object`。

typeof null // "object"

instanceof运算符

instanceof运算符返回一个布尔值,表示对象是否为某个构造函数的实例。
由于instanceof检查整个原型链,因此同一个实例对象,可能会对多个构造函数都返回true
instanceof运算符的一个用处,是判断值的类型。

var x = []
var f={}
x instanceof Array //true
f instanceof Object //true

instanceof运算符只能用于对象,不适用原始类型的值。

利用instanceof运算符,还可以解决,调用构造函数时,忘了加new命令的问题。

function Fn (f1, f2) {
  if (this instanceof Fn) {
    this._foo = f1;
    this._bar = b2;
  } else {
    return new Fn(f1, f2);
  }
}

Object.prototype.toString()

toString方法的作用是返回一个对象的字符串形式,默认情况下返回类型字符串。

var o1 = new Object();
o1.toString() //"[object Object]"

toString() 的应用:判断数据类型
Object.prototype.toString方法返回对象的类型字符串,因此可以用来判断一个值的类型。

var obj = {};
obj.toString() // "[object Object]"

上面代码调用空对象的toString方法,结果返回一个字符串object Object,其中第二个Object表示该值的构造函数。这是一个十分有用的判断数据类型的方法。

由于实例对象可能会自定义toString方法,覆盖掉Object.prototype.toString方法,所以为了得到类型字符串,最好直接使用Object.prototype.toString方法。通过函数的call方法,可以在任意值上调用这个方法,判断这个值的类型。

Object.prototype.toString.call(value)

上面代码表示对value这个值调用Object.prototype.toString方法。
不同数据类型的Object.prototype.toString方法返回值如下。

  • 数值:返回[object Number]
Object.prototype.toString.call(12) //"[object Number]"
  • 字符串:返回[object String]
Object.prototype.toString.call('ab')  //"[object String]"
  • 布尔值:返回[object Boolean]
Object.prototype.toString.call(true)  //"[object Boolean]"
  • undefined:返回[object Undefined]
Object.prototype.toString.call(undefined)  //"[object Undefined]"
  • null:返回[object Null]
Object.prototype.toString.call(null)  //"[object Null]"
  • 数组:返回[object Array]
Object.prototype.toString.call([])  //"[object Array]"
  • 函数:返回[object Function]
var f = function (){}
Object.prototype.toString.call(f)  //"[object Function]"

利用这个特性,可以写出一个比typeof运算符更准确的类型判断函数。

var type = function (o){
  var s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};

type({}); // "object"
type([]); // "array"
type(3); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"

未完待续

猜你喜欢

转载自www.cnblogs.com/qfstudy/p/9297356.html