如何检查值是否是JavaScript中的对象?
当前回答
我有一段代码片段可以使用。当没有给出整段代码时,我觉得很困惑,所以我自己创建了它:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunc()">Try it</button>
<script>
var abc = new Number();
// var abc = 4;
//this is a code variation which will give a diff alert
function myFunc()
{
if(abc && typeof abc === "object")
alert('abc is an object and does not return null value');
else
alert('abc is not an object');
}
</script>
</body>
</html>
其他回答
如果您想检查对象的原型是否仅来自object。过滤掉字符串、数字、数组、参数等。
function isObject (n) {
return Object.prototype.toString.call(n) === '[object Object]';
}
或作为单个表达式箭头函数(ES6+)
const isObject = n => Object.prototype.toString.call(n) === '[object Object]'
让我们在Javascript中定义“对象”。根据MDN文档,每个值都是对象或基元:
基元,基元值不是对象且没有任何方法的数据。JavaScript有7种原始数据类型:string、number、bigint、boolean、undefined、symbol和null。
什么是原始人?
3.“abc”真的无效的未定义
什么是对象(即不是基元)?
对象.原型Object.prototype派生的所有内容功能.原型对象作用函数C(){}--用户定义函数C.prototype——用户定义函数的原型属性:这不是Cs原型new C()--“new”-ing用户定义的函数数学阵列.原型阵列{“a”:1,“b”:2}--使用文字符号创建的对象new Number(3)--基元周围的包装器…许多其他事情。。。对象.create(null)从Object.create(null)派生的所有内容
如何检查值是否为对象
instanceof本身不起作用,因为它忽略了两种情况:
// oops: isObject(Object.prototype) -> false
// oops: isObject(Object.create(null)) -> false
function isObject(val) {
return val instanceof Object;
}
typeof x===“对象”无法工作,因为误报(null)和误报(函数):
// oops: isObject(Object) -> false
function isObject(val) {
return (typeof val === 'object');
}
Object.prototype.toString.call无法工作,因为所有基元都存在误报:
> Object.prototype.toString.call(3)
"[object Number]"
> Object.prototype.toString.call(new Number(3))
"[object Number]"
所以我使用:
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
@Daan的回答似乎也奏效:
function isObject(obj) {
return obj === Object(obj);
}
因为根据MDN文档:
Object构造函数为给定值创建对象包装器。如果该值为null或未定义,它将创建并返回一个空对象,否则,它将返回与给定值对应的类型的对象。如果该值已经是一个对象,它将返回该值。
第三种似乎有效的方法(不确定是否100%)是使用Object.getPrototypeOf,如果其参数不是对象,则抛出异常:
// these 5 examples throw exceptions
Object.getPrototypeOf(null)
Object.getPrototypeOf(undefined)
Object.getPrototypeOf(3)
Object.getPrototypeOf('abc')
Object.getPrototypeOf(true)
// these 5 examples don't throw exceptions
Object.getPrototypeOf(Object)
Object.getPrototypeOf(Object.prototype)
Object.getPrototypeOf(Object.create(null))
Object.getPrototypeOf([])
Object.getPrototypeOf({})
这取决于你所说的“是一个物体”。如果您想要所有非原语的内容,即可以设置新财产的内容,那么这应该可以做到:
function isAnyObject(value) {
return value != null && (typeof value === 'object' || typeof value === 'function');
}
它排除了基元(纯数字/NaN/Infinity、纯字符串、符号、true/false、undefined和null),但其他所有对象(包括Number、Boolean和String对象)都应返回true。注意,JS没有定义当与typeof一起使用时,应该返回哪些“主机”对象,例如窗口或控制台,因此很难用这样的检查来覆盖这些对象。
如果您想知道某个对象是“普通”对象,即它是作为文本{}创建的还是使用object.create(null)创建的,您可以这样做:
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
} else {
var prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
}
}
编辑2018:因为Symbol.toStringTag现在允许自定义Object.protoct.toString.call(…)的输出,所以上面的isPlainObject函数在某些情况下可能会返回false,即使对象以文本形式开始其生命。可以说,按照惯例,带有自定义字符串标记的对象不再是纯对象,但这进一步模糊了Javascript中的纯对象定义。
我从这个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
可随时使用的检查功能
function isObject(o) {
return null != o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]';
}
function isDerivedObject(o) {
return !isObject(o) &&
null != o &&
(typeof o === 'object' || typeof o === 'function') &&
/^\[object /.test(Object.prototype.toString.call(o));
}
// Loose equality operator (==) is intentionally used to check
// for undefined too
// Also note that, even null is an object, within isDerivedObject
// function we skip that and always return false for null
解释
在Javascript中,null、Object、Array、Date和函数都是对象。虽然,null有点做作。因此,最好先检查空值,以检测它是否为空。检查o==“object”的类型可确保o是一个对象。如果不进行此检查,Object.prototype.toString将毫无意义,因为它将返回任何对象,即使是未定义和null!例如:toString(undefined)返回[object undefined]!在typeofo=='object'检查之后,toString.call(o)是一个很好的方法来检查o是一个对象,还是一个派生对象,如Array、Date或函数。在isDerivedObject函数中,它检查o是否为函数。因为,函数也是一个对象,这就是它存在的原因。若并没有这样做,函数将返回false。示例:isDerivedObject(function(){})将返回false,但现在返回true。人们总是可以改变对象的定义。因此,可以相应地更改这些函数。
测验
函数isObject(o){返回null!=o&&typeof o==“对象”&&Object.pr原型.toString.call(o)==“[对象对象]”;}函数isDerivedObject(o){回来isObject(o)&&空!=o&&(类型o==“对象”| |类型o===“函数”)&&/^\[object/.test(object.protype.toString.call(o));}//测试//null是对象吗?控制台日志('是空的对象吗?',isObject(空));控制台日志('是否为null派生对象?',isDerivedObject(空));//1234是一个对象吗?控制台日志('1234是对象吗?',isObject(1234));控制台日志('1234是派生对象吗?',isDerivedObject(1234));//新编号(1234)是对象吗?控制台日志('新编号(1234)是对象吗?',isObject(新编号(1234)));控制台日志('新编号(1234)是派生对象吗?',isDerivedObject(1234));//函数对象是对象吗?控制台日志('是(new(function(){}))对象吗?',isObject((new(函数(){})));控制台日志(“(new(function(){}))是派生对象吗?”,isObject((new(函数(){})));//{}是对象吗?控制台日志(“是{}对象吗?”,isObject({}));控制台日志(“{}是派生对象吗?”,isDerivedObject({}));//Array是对象吗?控制台日志('数组是对象吗?',isObject([]))控制台日志('数组是派生对象吗?',isDerivedObject([]))//Date是对象吗?控制台日志('日期是对象吗?',isObject(新日期()));控制台日志('日期是派生对象吗?',isDerivedObject(新日期()));//函数是对象吗?控制台日志('函数是对象吗?',isObject(函数(){}));控制台日志('函数是派生对象吗?',isDerivedObject(函数(){}));
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie