返回

七大基本判断问题,通俗解释一次掌握

前端

一、判断属性来源于对象本身还是原型链

在 JavaScript 中,对象可以继承自其他对象,这种继承关系称为原型链。当我们访问一个对象的属性时,JavaScript 会沿着原型链查找该属性。如果在该对象上找到了该属性,则返回该属性的值;如果未找到,则继续沿着原型链查找,直到找到该属性或到达原型链的末尾。

我们可以使用 hasOwnProperty() 方法来判断一个属性来源于对象本身还是原型链。hasOwnProperty() 方法返回一个布尔值,如果该属性来源于对象本身,则返回 true;如果该属性来源于原型链,则返回 false

const obj = {
  name: "John Doe",
};

console.log(obj.hasOwnProperty("name")); // true
console.log(obj.hasOwnProperty("age")); // false

二、判断对象的类型

我们可以使用 typeof 运算符来判断一个对象的类型。typeof 运算符返回一个字符串,该字符串表示该对象的类型。

const str = "Hello world";
const num = 123;
const bool = true;
const arr = [1, 2, 3];
const obj = {
  name: "John Doe",
};

console.log(typeof str); // "string"
console.log(typeof num); // "number"
console.log(typeof bool); // "boolean"
console.log(typeof arr); // "object"
console.log(typeof obj); // "object"

注意:typeof 运算符对于数组和对象返回的结果都是 "object",因此我们需要使用其他方法来判断数组和对象。

三、判断数组是否为空

我们可以使用 length 属性来判断数组是否为空。length 属性返回数组中元素的数量。如果数组中没有元素,则 length 属性的值为 0

const arr = [];
const arr2 = [1, 2, 3];

console.log(arr.length); // 0
console.log(arr2.length); // 3

四、判断对象是否相等

我们可以使用 === 运算符来判断两个对象是否相等。=== 运算符比较两个对象的引用,如果两个对象的引用相同,则返回 true;否则,返回 false

const obj1 = {
  name: "John Doe",
};
const obj2 = {
  name: "John Doe",
};

console.log(obj1 === obj2); // false

注意:=== 运算符对于数组和对象返回的结果都是 false,因为数组和对象是引用类型。

五、判断字符串是否为空

我们可以使用 length 属性来判断字符串是否为空。length 属性返回字符串中字符的数量。如果字符串中没有字符,则 length 属性的值为 0

const str1 = "";
const str2 = "Hello world";

console.log(str1.length); // 0
console.log(str2.length); // 11

六、判断函数是否已定义

我们可以使用 typeof 运算符来判断函数是否已定义。typeof 运算符返回一个字符串,该字符串表示该函数的类型。如果函数已定义,则 typeof 运算符返回 "function";否则,返回 "undefined"

function greet() {
  console.log("Hello world");
}

console.log(typeof greet); // "function"

const undeclaredFunction = undefined;

console.log(typeof undeclaredFunction); // "undefined"

七、判断变量是否已声明

我们可以使用 typeof 运算符来判断变量是否已声明。typeof 运算符返回一个字符串,该字符串表示该变量的类型。如果变量已声明,则 typeof 运算符返回该变量的类型;否则,返回 "undefined"

let name = "John Doe";

console.log(typeof name); // "string"

let undeclaredVariable;

console.log(typeof undeclaredVariable); // "undefined"