js实现判断
判断数据类型
使用typeof操作符可以判断基本数据类型,但对于对象和数组需要更精确的方法。
const num = 42;
const str = "hello";
const bool = true;
const arr = [1, 2, 3];
const obj = { key: "value" };
console.log(typeof num); // "number"
console.log(typeof str); // "string"
console.log(typeof bool); // "boolean"
console.log(typeof arr); // "object"
console.log(typeof obj); // "object"
精确类型判断
使用Object.prototype.toString.call()方法可以获取更精确的类型信息。
console.log(Object.prototype.toString.call(num)); // "[object Number]"
console.log(Object.prototype.toString.call(str)); // "[object String]"
console.log(Object.prototype.toString.call(bool)); // "[object Boolean]"
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(obj)); // "[object Object]"
数组判断
专门判断数组可以使用Array.isArray()方法。
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false
空值判断
检查变量是否为null或undefined。
const emptyVar = null;
const undefVar = undefined;
console.log(emptyVar === null); // true
console.log(undefVar === undefined); // true
对象属性判断
使用in操作符或hasOwnProperty方法检查对象是否包含某个属性。
const person = { name: "Alice", age: 25 };
console.log("name" in person); // true
console.log(person.hasOwnProperty("age")); // true
console.log("toString" in person); // true (继承属性)
console.log(person.hasOwnProperty("toString")); // false
相等性判断
使用===严格相等和==宽松相等进行比较。
console.log(5 == "5"); // true
console.log(5 === "5"); // false
自定义类型判断
通过构造函数或instanceof判断自定义类型。
function Person(name) {
this.name = name;
}
const alice = new Person("Alice");
console.log(alice instanceof Person); // true
console.log(alice.constructor === Person); // true
函数判断
检查变量是否为函数类型。
function greet() {
console.log("Hello");
}
console.log(typeof greet === "function"); // true
NaN判断
使用isNaN()或Number.isNaN()判断NaN值。
console.log(isNaN("text")); // true (会先尝试转换为数字)
console.log(Number.isNaN("text")); // false (不会进行类型转换)
console.log(Number.isNaN(NaN)); // true
真值判断
在条件语句中自动转换为布尔值。

const truthy = "hello";
const falsy = "";
if (truthy) {
console.log("truthy"); // 会执行
}
if (falsy) {
console.log("falsy"); // 不会执行
}






