我知道(数组的实例),但是我如何测试一个对象?
var c = {};
if ( c instanceof XXXX) {
// should get thru
}
var s = "abscdef";
if ( s instanceof XXXX) {
// should not get thru
}
var a = [];
if ( a instanceof XXXX) {
// should not get thru
}
最佳答案
function isObject(c) {
return c instanceof Object
&& !(c instanceof Array)
&& !(c instanceof Function)
}
Array
和 Function
检查是必要的,因为 JavaScript 数组也是对象(假设您不希望函数返回 true
对于数组或函数参数)
示例输出:
isObject([])
> false
isObject({})
> true
isObject(1)
> false
isObject('something')
> false
isObject(isObject)
> false
关于Javascript:如何测试一个对象是一个对象(而不是数组或字符串)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24138582/