温馨提示×

js怎样判断对象的数据类型

发布时间:2022-03-24 11:42:26 来源:亿速云 阅读:139 作者:小新 栏目:web开发

这篇文章主要介绍js怎样判断对象的数据类型,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

判断对象的数据类型

使用Object.prototype.toString配合闭包来实现对象数据类型的判断:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isArray = isType('Array')([1, 2, 3])

console.log(isArray)
> Result: true

上面的代码相当于:

function isType(type){
    return function (target) {
        return `[object ${type}]` === Object.prototype.toString.call(target)
    }
}

isType('Array')([1,2,3])
> Result: true

或者:

const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isString = isType('String')
const res = isString(('1'))

console.log(res)
> Result: true

以上是“js怎样判断对象的数据类型”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js