返回

赋予JavaScript对象以生命:常用方法详解

前端

好的,让我们来写一篇文章,介绍JavaScript中Object的常用方法。

在平时学习中,经常会用到Object对象上得以一些自带的方法。比如类型判断的Object.prototype.toString()、获取对象的keyObject.keys()、等等。下面就让我们来详细了解一下这些常用方法吧!

类型判断

Object.prototype.toString()方法可以判断一个变量的类型。它返回一个字符串,表示变量的类型。例如:

console.log(Object.prototype.toString.call(1)); // "[object Number]"
console.log(Object.prototype.toString.call("hello")); // "[object String]"
console.log(Object.prototype.toString.call(true)); // "[object Boolean]"

获取键

Object.keys()方法可以获取一个对象的所有键。它返回一个数组,包含对象的所有键。例如:

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

console.log(Object.keys(person)); // ["name", "age", "city"]

遍历

for...in循环可以遍历一个对象的所有键。例如:

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

for (const key in person) {
  console.log(key, person[key]);
}

输出结果:

name John
age 30
city New York

合并

Object.assign()方法可以将两个或多个对象合并成一个新的对象。例如:

const person1 = {
  name: "John",
  age: 30
};

const person2 = {
  city: "New York"
};

const mergedPerson = Object.assign({}, person1, person2);

console.log(mergedPerson); // { name: "John", age: 30, city: "New York" }

冻结

Object.freeze()方法可以冻结一个对象,使其无法修改。例如:

const person = {
  name: "John",
  age: 30
};

Object.freeze(person);

person.name = "Jane"; // 报错:TypeError: Cannot assign to read only property 'name' of object '[object Object]'

密封

Object.seal()方法可以密封一个对象,使其无法添加或删除属性,但可以修改属性的值。例如:

const person = {
  name: "John",
  age: 30
};

Object.seal(person);

person.name = "Jane"; // 成功

person.city = "New York"; // 报错:TypeError: Cannot add property 'city' to object '[object Object]'

delete person.name; // 报错:TypeError: Cannot delete property 'name' of object '[object Object]'

定义属性

Object.defineProperty()方法可以定义一个对象的属性。例如:

const person = {};

Object.defineProperty(person, "name", {
  value: "John",
  writable: false,
  enumerable: true,
  configurable: false
});

console.log(person.name); // "John"

person.name = "Jane"; // 报错:TypeError: Cannot assign to read only property 'name' of object '[object Object]'

delete person.name; // 报错:TypeError: Cannot delete property 'name' of object '[object Object]'

好了,以上就是JavaScript中Object对象的常用方法。希望这篇文章能对你有所帮助!