繁体   English   中英

有没有办法检查普通的香草 javascript object 而不是任何其他特殊类型的 object(即日期)?

[英]Is there a way to check for just a plain vanilla javascript object as opposed to any other special kind of object (i.e. Date)?

我尝试使用 instanceof 但它无法区分{}[]Date

例如,如果我想创建一个这样的 if 树:

function foo(someVar){
  if (/*someVar is an {}*/) {
  } else if (/*someVar is an []*/) {
  } else { //someVar could be a String or a Date or anything
  }
}

如果条件,我该如何写? 任何帮助将不胜感激,谢谢!

检查某个东西是否是“普通对象”首先想到的是看看它是否没有原型。

所以我想我会这样写:

function foo(someVar){
  if (typeof "someVar" === 'object' && someVar.prototype === undefined) {

  } else if (Array.isArray(someVar)) {

  } else {

  }
}

检查值是否为数组类型,您可以使用Array.isArray()例如:

 var first=Array.isArray([1,'fruits',3]) var second=Array.isArray('foo') console.log(first) console.log(second)

To check if The value is of type object things get a little bit difficult since type object is an umbrella for too many types like Function,array... but you could use this function, it's by no means is going to work for all types因为它不排除所有类型,但排除了大多数类型

 ob=[] function isObject(obj) { if(obj === Object(obj)){ return Array.isArray(obj)?false:(typeof obj === 'function'?false:(Object.prototype.toString.call(obj) === '[object Date]'?false:(Object.prototype.toString.call(obj) === '[object Number]'?false:(Object.prototype.toString.call(obj) === '[object Math]'?false:true))))} else return false } console.log(isObject(ob))

要检查类型日期,您可以使用它

Object.prototype.toString.call(obj) === '[object Date]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM