在 JavaScript 中检查值是否为对象
在 JavaScript 中,定义的每个值要么是对象,要么是基元。任何不是对象且没有任何方法的值都称为基元。任何不是原始的都是一个对象。
在本教程中,我们将检查一个值是否是一个对象。
我们将在 instanceof
方法的帮助下检查该值,该方法在运行时返回对象的类型。
在下面的示例中,如果值是对象类型,该函数将返回 true
。
const test = {};
function isObject(val) {
return val instanceof Object;
}
console.log(isObject(test));
输出:
true
但这种方法不适用于所有情况。isObject(Object.prototype)
和 isObject(Object.create(null))
将返回 False。
我们可以使用 typeof()
函数检查对象的类型。
例如,
const test = {};
function isObject(val) {
return (typeof val === 'object');
}
console.log(isObject(test));
输出:
true
此方法也不适用于所有测试用例。它将为空测试用例返回假阳性,为函数返回假阴性。isObject(Object)
也将返回 false
。
我们还可以使用此函数定义另一个函数来解决上述限制。
请参考下面的代码。
const test = {};
function t() {};
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
console.log(isObject(test));
console.log(isObject(t));
输出:
true
true
如果值为 NULL,则上述示例中的函数返回 False。如果该值是 function
类型或 object
类型,则返回 true。否则,它返回 False。
我们可以定义更多这样的函数来完成基于对象的构造函数和类的工作。
例如,
const test = {};
function isObject(obj) {
return obj === Object(obj);
}
function isObject2(obj) {
return obj.constructor.toString().indexOf("Object") > -1;
}
console.log(isObject(test));
console.log(isObject2(test));
输出:
true
true
在上面的例子中,我们创建了两个函数来检查给定的值是否是一个对象。
如果 getPrototypeOf
方法的参数不是对象,它将抛出异常。我们可以用它来检查给定值的类的类型。
例如,
const test = {};
const object1 = Object.create(test);
console.log(Object.getPrototypeOf(object1) === test);
输出:
true
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。