如何检查值是否是JavaScript中的对象?
当前回答
一个基于Matt Fenwick对其完整答案的第三个选项的NodeJS控制台实验。只要稍微调整一下就能判断真假。
以下对象测试返回false。
> if(Object.getPrototypeOf('v') === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(1) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(false) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(['apple']) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
对象将返回true。
> if(Object.getPrototypeOf({'this':10}) === Object.prototype){console.log(true);}else{console.log(false);}
true
undefined
其他回答
如果您想检查对象的原型是否仅来自object。过滤掉字符串、数字、数组、参数等。
function isObject (n) {
return Object.prototype.toString.call(n) === '[object Object]';
}
或作为单个表达式箭头函数(ES6+)
const isObject = n => Object.prototype.toString.call(n) === '[object 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
Ramda函数库具有检测JavaScript类型的出色功能。
完整功能的释义:
function type(val) {
return val === null ? 'Null' :
val === undefined ? 'Undefined' :
Object.prototype.toString.call(val).slice(8, -1);
}
当我意识到解决方案是多么简单和美丽时,我不得不笑了。
Ramda文档中的用法示例:
R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"
我从这个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
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 不可变与可变类型
- 很好的初学者教程socket.io?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?