前端开发人必会的十大 JavaScript 对象方法

AI 概述
本文介绍了10个前端开发中常被忽视但极其有用的JavaScript内置对象方法。包括用于安全检查属性的Object.hasOwn()、数组分组的Object.groupBy()、基于原型创建对象的Object.create(),以及遍历和转换对象的keys、values、entries和fromEntries。此外还涵盖了合并对象的Object.assign(),以及防止对象被修改的Object.seal()和Object.freeze()。合理使用这些方法能让代码更简洁、健壮,提升开发效率。
目录
文章目录隐藏
  1. Object.hasOwn()
  2. Object.groupBy()
  3. Object.create()
  4. Object.keys()
  5. Object.values()
  6. Object.fromEntries()
  7. Object.assign()
  8. Object.seal()
  9. Object.freeze()

前端开发人必会的十大 JavaScript 对象方法

Objects 在 JavaScript 中无处不在。许多前端开发者每天都在使用对象,但并没有充分利用内置的对象方法。本文通过示例介绍 10 个 Object 方法。

Object.hasOwn()

  • 安全地检查属性;
  • 避免原型链带来的问题。
const user = {
  name: 'Datta',
  age: 25,
};
console.log(Object.hasOwn(user, 'name')); // true
console.log(Object.hasOwn(user, 'age')); // true
console.log(Object.hasOwn(user, 'location')); // false (property is undefined)
console.log(Object.hasOwn(user, 'toString')); // false (property is inherited from Object.prototype)

Object.groupBy()

  • 将数组数据分组为对象;
  • reduce()更简洁的替代方案。
const products = [
  { name: "apples", category: "fruits" },
  { name: "oranges", category: "fruits" },
  { name: "potatoes", category: "vegetables" },
  { name: "bananas", category: "fruits" },
  { name: "carrots", category: "vegetables" },
];

const groupedByCategory = Object.groupBy(products, (product) => {
  return product.category;
});

console.log(groupedByCategory);
// {
//   fruits: [{
//   category: "fruits",
//   name: "apples"
// }, {
//   category: "fruits",
//   name: "oranges"
// }, {
//   category: "fruits",
//   name: "bananas"
// }],
//   vegetables: [{
//   category: "vegetables",
//   name: "potatoes"
// }, {
//   category: "vegetables",
//   name: "carrots"
// }]
// }

Object.create()

  • 基于原型的继承;
  • 在不使用构造函数的情况下创建对象。
const person = {
  name: 'Datta',
  greet() {
    return `Hello my name is ${this.name}`
  },
}

const student = Object.create(person)
student.name = 'Jhon';

console.log(student.greet()) // "Hello my name is Jhon"

Object.keys()

  • 遍历对象属性;
  • 校验对象是否为空。
const car = {
  brand: "Toyota",
  model: "Camry",
  year: 2023,
}
const keys = Object.keys(car) // ["brand", "model", "year"]

Object.values()

  • 从 API 数据中提取值;
  • 对值进行求和等操作。
const car = {
  brand: 'Toyota',
  model: 'Camry',
  year: 2023,
};
const values= Object.values(car); // ["Toyota", "Camry", 2023]

Object.entries()

  • 将对象转换为 Map;
  • 使用for...of进行遍历。
const car = {
  brand: 'Toyota',
  model: 'Camry',
  year: 2023,
}

const data = Object.entries(car) // [["brand", "Toyota"], ["model", "Camry"], ["year", 2023]]

Object.fromEntries()

  • 将键值对重新转换为对象;
  • 清理或转换 API 数据。
const entries = [
  ['name', 'Datta'],
  ['age', 25],
  ['country', 'India'],
];

const user = Object.fromEntries(entries);

console.log(user);// { name: "Datta", age: 25, country: "India" }

Object.assign()

  • 合并对象;
  • 创建浅拷贝。
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);
console.log(target); // { a: 1, b: 4, c: 5 } (target is modified)
console.log(returnedTarget); // { a: 1, b: 4, c: 5}

// shallow copy
const obj = { x: 10, y: 20 };
const clone = Object.assign({}, obj);
console.log(clone); // { x: 10, y: 20 }

// The original 'obj' is unchanged
console.log(obj); // { x: 10, y: 20 }

Object.seal()

  • 当对象结构必须保持不变时使用;
  • 防止意外删除属性。
const person = {
  name: 'Datta',
  age: 25,
};

// Seal the object: no new properties, no deletions allowed
Object.seal(person);

// --- Allowed Actions ---
person.name = 'Bob'; // Modify existing property (works)
console.log(person.name); // "Bob"

// --- Forbidden Actions (fail silently or throw errors in strict mode) ---
person.city = 'New York'; // Add new property (fails)
delete person.age; // Delete existing property (fails)

console.log(person); // { name: 'Bob', age: 25 } (still has original props, name updated)

Object.freeze()

  • 防止意外修改;
  • 常用于状态管理。
const person = {
  firstName: 'Datta',
  lastName: 'Chavhan',
  age: 25,
};
// Freeze the object
Object.freeze(person);

// Attempt to change an existing property (will not work)
person.age = 51;
person['firstName'] = 'Jane';

// Attempt to add a new property (will not work)
person.eyeColor = 'blue';

// Attempt to delete a property (will not work)
delete person.lastName;

// The original object remains unchanged
console.log(person);
// Output: { firstName: "Datta", lastName: "Chavhan", age: 25 }

作为前端开发人可以开始在日常编码中使用这 10 个 JavaScript 对象方法,你会很快注意到代码变得更加简洁,也更加强大。

以上关于前端开发人必会的十大 JavaScript 对象方法的文章就介绍到这了,更多相关内容请搜索码云笔记以前的文章或继续浏览下面的相关文章,希望大家以后多多支持码云笔记。

「点点赞赏,手留余香」

16

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 admin@mybj123.com 进行投诉反馈,一经查实,立即处理!
重要:如软件存在付费、会员、充值等,均属软件开发者或所属公司行为,与本站无关,网友需自行判断
码云笔记 » 前端开发人必会的十大 JavaScript 对象方法

发表回复