JSでデータ型を判断する方法

JSでデータ型を判断する方法

Xiaoroubaoの以前のブログで、データ型判断するためのJSメソッドの完全な波を共有していることに基づいて、より包括的なメソッドを共有します。以前の共有コンテンツとの違いは、この記事では、メソッドを宣言するだけで、次のことができることです。複数のデータ型を判断するために使用されます。


コードは次のように表示されます。
/**
 * 判断某个数据是否为某种类型
 * by 小肉包
 * @params type    想要判断的类型 
 * @params value    想要判断的数据
 * 返回值 :布尔值(true / false)
 */
 function belongTo(type, value) {
    
    
            switch (type) {
    
    
                case Number:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Number]'
                    }
                case Boolean:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Boolean]'
                    }
                case String:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object String]'
                    }
                case Array:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Array]'
                    }
                case Object:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Object]'
                    }
                case Function:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Function]'
                    }
                case null:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Null]'
                    }
                case undefined:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Undefined]'
                    }
                case Date:
                    {
    
    
                        return Object.prototype.toString.call(value) === '[object Date]'
                    }
                default:
                    {
    
    
                        return false;
                    }
            }
        }

//使用举例:
console.log( belongTo(Number, 52) )      // true 

console.log( belongTo(String, '这是字符串吗') )      // true 

let arr = [1,5,12]
let a=500

console.log( belongTo(Array, arr) )      // true 

console.log( belongTo(String, a) )      // false

私の友達に助けをもたらすことを願っています!私の個人ブログsongdongの章へようこそ

おすすめ

転載: blog.csdn.net/weixin_47160442/article/details/112874278