美文网首页
js判断值的类型

js判断值的类型

作者: icaojinyu | 来源:发表于2019-01-25 10:46 被阅读0次

JavaScript 有三种方法,可以确定一个值到底是什么类型。

  • typeof运算符
  • instanceof运算符
  • Object.prototype.toString()方法
  1. typeof运算符可以返回一个值的数据类型。
typeof undefined  // "undefined"
typeof null  // "object"
----
typeof 123  // "number"
typeof 'hello'  // "string"
typeof true  // "boolean"
typeof false  // "boolean"
----
typeof window  // "object"
typeof {}  // "object"
typeof []  // "object"
typeof function fn(){}  // "function"

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

const arr = [1,2,3]
arr.__proto__ === Array.prototype  // true
Array.prototype.__proto__ === Object.prototype  // true
arr instanceof Array  // true
arr instanceof Object  // true

3.Object.prototype.toString()可以看出一个值到底是什么类型。一般用这个方法来判断引用类型的值,基本类型的值用typeof就足够了。

Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([])  // "[object Array]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call(new Date())  // "[object Date]"

写一个函数,判断给定的值是否为数组

function isArray(val) {
  return Object.prototype.toString.call(val) === '[object Array]'
}
const arr = [1,2,3]
isArray(arr)  // true
isArray({})  // false

相关文章

网友评论

      本文标题:js判断值的类型

      本文链接:https://www.haomeiwen.com/subject/patmjqtx.html