Home > Web Front-end > JS Tutorial > Introduction to methods of judging data types in JavaScript (code)

Introduction to methods of judging data types in JavaScript (code)

不言
Release: 2019-03-29 09:48:15
forward
2356 people have browsed it

The content of this article is an introduction (code) about the method of judging JavaScript data type. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. The commonly used typeof

is not friendly to the judgment of array, object, and null. You can see the execution results in the figure below.

Introduction to methods of judging data types in JavaScript (code)

var obj = {
  number:123,
  string: '123',
  bool: true,
  obj: {},
  arr: [],
  n: null,
  undef: undefined,
  fn: function () {}
}

for(key in obj) {
  console.log(key + ": " + typeof obj[key])
}
Copy after login

2. instanceof

instanceof tests whether the constructor's prototype attribute appears anywhere in the object's prototype chain.
If you understand the prototype chain, you will know the complexity of the prototype chain. The value obtained by instanceof is not fixed. It will search along the prototype chain. The most obvious thing is that all basic data types inherit from Object .protype.

[任何数据类型] instanceof Object
> true
Copy after login

As shown below:

Introduction to methods of judging data types in JavaScript (code)

3.Final solution: Object.prototype.toString.call()

The following is the best, most comprehensive, and most effective compatibility solution:
There are two implementation methods (prototype method and global method) below, which you can choose according to your own needs.

(function () {
  function isType(type,data) {
    // data是全局方法时使用的,原型方法可不填
    return Object.prototype.toString.call(data || this) === '[object ' + type + ']'
  }
  // 全局方法支持null和undefined
  // window.isType = isType

  // 添加到数据类型的原型中,不支持null和undefined
    Object.defineProperty(Object.prototype,'isType',{
      value:isType,
      writable:true,
        enumerable:false,
        configurable:true
    });
})()
Copy after login

Usage:

var str = 'abc';
// 全局方法
isType('String', str) // True

// 原型方法
str.isType('String')
Copy after login

Test code:

var obj = {
  test: {
    number:123,
    string: '123',
    obj: {},
    bool: true,
    arr: [],
    n: null,
    undef: undefined,
    fn: function () {

    }
  }
}
// 原型方法不支持null和undefined,请用“===”
console.log(obj.test.number.isType('Number'))
console.log(obj.test.number.isType('String'))

console.log(obj.test.string.isType('String'))
console.log(obj.test.string.isType('Number'))

console.log(obj.test.obj.isType('Object'))
console.log(obj.test.obj.isType('Array'))

console.log(obj.test.arr.isType('Array'))
console.log(obj.test.arr.isType('Object'))


console.log(obj.test.fn.isType('Function'))
console.log(obj.test.fn.isType('Object'))
Copy after login

Introduction to methods of judging data types in JavaScript (code)

This article is all over here, more others For exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website! ! !

The above is the detailed content of Introduction to methods of judging data types in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template