📅  最后修改于: 2023-12-03 14:55:44.602000             🧑  作者: Mango
在 JavaScript 中,我们可以使用 typeof
运算符检查给定的变量类型。如果变量的类型是 "object",它可能是 JavaScript 中的一个对象。
不过,这种方法的问题是,如果一个值为 null,它的类型也是 "object",但它不是 JavaScript 中的对象。
因此,为了确保一个值是 JavaScript 中的对象,我们可以使用 Object.prototype.toString.call()
方法。
代码如下:
const myObject = { name: "John" };
console.log(Object.prototype.toString.call(myObject));
// 输出: "[object Object]"
const myArray = [1, 2, 3];
console.log(Object.prototype.toString.call(myArray));
// 输出: "[object Array]"
const myFunction = function() { return 2 + 2 };
console.log(Object.prototype.toString.call(myFunction));
// 输出: "[object Function]"
const myString = "Hello world";
console.log(Object.prototype.toString.call(myString));
// 输出: "[object String]"
const myNumber = 42;
console.log(Object.prototype.toString.call(myNumber));
// 输出: "[object Number]"
const myBoolean = true;
console.log(Object.prototype.toString.call(myBoolean));
// 输出: "[object Boolean]"
const myNull = null;
console.log(Object.prototype.toString.call(myNull));
// 输出: "[object Null]"
请注意,如果你想检查一个值是否为 null,你可以使用检查 null === yourVariable
来完成。
这就是如何检查一个值是否是 JavaScript 中的对象。