如何检查值是否是JavaScript中的对象?
当前回答
underscore.js提供了以下方法来确定某个对象是否真的是对象:
_.isObject = function(obj) {
return obj === Object(obj);
};
更新
由于V8之前的一个bug和轻微的微速度优化,自underscore.js 1.7.0(2014年8月)以来,该方法如下:
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
其他回答
Object.pr原型.toString.call(myVar)将返回:
“[object object]”如果myVar是对象“[object Array]”如果myVar是数组等
有关这方面的更多信息,以及为什么它是typeof的一个很好的替代品,请查看本文。
我从这个SO问题中找到了一种“新”方法来进行这种类型检查:为什么instanceof对某些文本返回false?
在此基础上,我创建了一个类型检查函数,如下所示:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return false; //fallback for null or undefined
}
}
那么你可以这样做:
console.log(isVarTypeOf('asdf', String)); // returns true
console.log(isVarTypeOf(new String('asdf'), String)); // returns true
console.log(isVarTypeOf(123, String)); // returns false
console.log(isVarTypeOf(123, Number)); // returns true
console.log(isVarTypeOf(new Date(), String)); // returns false
console.log(isVarTypeOf(new Date(), Number)); // returns false
console.log(isVarTypeOf(new Date(), Date)); // returns true
console.log(isVarTypeOf([], Object)); // returns false
console.log(isVarTypeOf([], Array)); // returns true
console.log(isVarTypeOf({}, Object)); // returns true
console.log(isVarTypeOf({}, Array)); // returns false
console.log(isVarTypeOf(null, Object)); // returns false
console.log(isVarTypeOf(undefined, Object)); // returns false
console.log(isVarTypeOf(false, Boolean)); // returns true
这在Chrome 56、Firefox 52、Microsoft Edge 38、Internet Explorer 11和Opera 43上进行了测试
编辑:如果您还想检查变量是否为空或未定义,则可以使用以下方法:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
var a = undefined, b = null;
console.log(isVarTypeOf(a, undefined)) // returns true
console.log(isVarTypeOf(b, undefined)) // returns true
console.log(isVarTypeOf(a, null)) // returns true
财务评论更新:接受挑战:D
如果要松散比较对象,可以尝试以下方法:
function isVarTypeOf(_var, _type, looseCompare){
if (!looseCompare){
try {
return _var.constructor === _type;
} catch(ex){
return _var == _type;
}
} else {
try{
switch(_var.constructor){
case Number:
case Function:
case Boolean:
case Symbol:
case Date:
case String:
case RegExp:
// add all standard objects you want to differentiate here
return _var.constructor === _type;
case Error:
case EvalError:
case RangeError:
case ReferenceError:
case SyntaxError:
case TypeError:
case URIError:
// all errors are considered the same when compared to generic Error
return (_type === Error ? Error : _var.constructor) === _type;
case Array:
case Int8Array:
case Uint8Array:
case Uint8ClampedArray:
case Int16Array:
case Uint16Array:
case Int32Array:
case Uint32Array:
case Float32Array:
case Float64Array:
// all types of array are considered the same when compared to generic Array
return (_type === Array ? Array : _var.constructor) === _type;
case Object:
default:
// the remaining are considered as custom class/object, so treat it as object when compared to generic Object
return (_type === Object ? Object : _var.constructor) === _type;
}
} catch(ex){
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
}
这样,你就可以像finance的评论一样:
isVarTypeOf(new (function Foo(){}), Object); // returns false
isVarTypeOf(new (function Foo(){}), Object, true); // returns true
or
Foo = function(){};
Bar = function(){};
isVarTypeOf(new Foo(), Object); // returns false
isVarTypeOf(new Foo(), Object, true); // returns true
isVarTypeOf(new Bar(), Foo, true); // returns false
isVarTypeOf(new Bar(), Bar, true); // returns true
isVarTypeOf(new Bar(), Bar); // returns true
试试这个
if (objectName instanceof Object) {
alert('Not an object');
}
else {
alert('An object');
}
大多数类型的obj[index]=='object'被使用,但它也会返回作为对象的函数和#document。这取决于你是否需要将其包括在结果中。
基本上,您可以通过检查控制台中的输出来过滤特定元素是否为对象的测试代码。在这里,您可以仅为示例运行代码:
函数cekObject(obj,index){if(!obj.tagName){//测试用例#1if(对象类型==“对象”){console.log('obj['+index+']被列为对象');} }}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js“></script><脚本>函数updateFilters(){var对象=$('.j-image');$('.juicer feed').empty();for(对象中的var索引){cekObject(对象[index],索引);}; }</script><ul class=“榨汁机饲料”数据饲料id=“chetabahana”数据after=“updateFilters()”></ul><script src=“https://assets.juicer.io/embed.js“></script>
这是一个老问题,但我想把它留在这里。大多数人都在检查变量是否为{},这意味着一个键值配对,而不是JavaScript用于给定对象的下划线构造,因为老实说,JavaScript中的大部分内容都是一个对象。所以把它从路上拿开。如果你这样做。。。
let x = function() {}
typeof x === 'function' //true
x === Object(x) // true
x = []
x === Object(x) // true
// also
x = null
typeof null // 'object'
大多数时候,我们想要的是知道我们是否有来自API的资源对象或从ORM返回的数据库调用。然后,我们可以测试是否不是数组、是否为null、是否为“function”类型、是否为Object
// To account also for new Date() as @toddmo pointed out
x instanceof Object && x.constructor === Object
x = 'test' // false
x = 3 // false
x = 45.6 // false
x = undefiend // false
x = 'undefiend' // false
x = null // false
x = function(){} // false
x = [1, 2] // false
x = new Date() // false
x = {} // true
推荐文章
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?
- 避免浏览器弹出窗口拦截器
- getJSON调用中的错误处理
- 我看到VARCHAR(255)如此频繁地使用(而不是其他长度),有什么好的原因吗?
- 如何快速清除JavaScript对象?
- 重要的样式