当前位置: 首页 > news >正文

【JS】JS基础-对象处理方法整合

对象处理方法工具手册

文章目录

    • 1. 对象创建和属性定义
      • 创建对象
      • 属性定义
    • 2. 属性描述符相关 API
    • 3. 对象遍历和迭代 API
    • 4. 对象复制和合并 API
      • 浅拷贝
      • 深拷贝
    • 5. 对象合并和组合 API
    • 6. 原型相关 API
    • 7. 对象冻结和密封 API
    • 8. 对象比较和转换 API
    • 9. 现代 ES6+ 对象 API
    • 10. 实用对象操作模式
      • 对象解构
      • 对象变换
    • 11. 高级对象模式
      • 工厂模式
      • 构造函数模式
      • 类语法 (ES6)

1. 对象创建和属性定义

创建对象

// 字面量创建
const obj1 = { name: "John", age: 30 };// 构造函数创建
const obj2 = new Object();
obj2.name = "Jane";// Object.create() - 创建带有原型的对象
const prototypeObj = { greet() { return "Hello"; } };
const obj3 = Object.create(prototypeObj);// Object.fromEntries() - 键值对数组转对象
const entries = [['name', 'Mike'], ['age', 25]];
const obj4 = Object.fromEntries(entries);

属性定义

// Object.defineProperty()
const obj = {};
Object.defineProperty(obj, 'name', {value: 'John',writable: true,      // 可写enumerable: true,    // 可枚举configurable: true   // 可配置
});// Object.defineProperties()
Object.defineProperties(obj, {age: {value: 30,writable: false},email: {value: 'john@example.com',enumerable: true}
});

2. 属性描述符相关 API

const obj = { name: "John", age: 30 };// 获取属性描述符
const desc = Object.getOwnPropertyDescriptor(obj, 'name');
console.log(desc);
// { value: "John", writable: true, enumerable: true, configurable: true }// 获取所有自身属性的描述符
const allDesc = Object.getOwnPropertyDescriptors(obj);// 检查属性是否存在
console.log(obj.hasOwnProperty('name')); // true
console.log(Object.hasOwn(obj, 'name')); // true (ES2022)// 属性枚举状态检查
Object.defineProperty(obj, 'hiddenProp', {value: 'secret',enumerable: false
});

3. 对象遍历和迭代 API

const person = {name: "Alice",age: 28,city: "New York"
};// 获取所有可枚举的自身属性名
const keys = Object.keys(person); // ["name", "age", "city"]// 获取所有可枚举的自身属性值
const values = Object.values(person); // ["Alice", 28, "New York"]// 获取所有可枚举的自身属性键值对
const entries = Object.entries(person); 
// [["name", "Alice"], ["age", 28], ["city", "New York"]]// 获取所有自身属性名(包括不可枚举)
const allKeys = Object.getOwnPropertyNames(person);// 获取所有 Symbol 属性
const symbolKeys = Object.getOwnPropertySymbols(person);

4. 对象复制和合并 API

浅拷贝

const original = { a: 1, b: { c: 2 } };// 扩展运算符
const shallowCopy1 = { ...original };// Object.assign()
const shallowCopy2 = Object.assign({}, original);// 注意:浅拷贝只复制第一层,嵌套对象仍是引用

深拷贝

// 简单深拷贝(有限制)
const deepCopy1 = JSON.parse(JSON.stringify(original));// 自定义深拷贝函数
function deepClone(obj) {if (obj === null || typeof obj !== 'object') return obj;if (obj instanceof Date) return new Date(obj);if (obj instanceof Array) return obj.map(item => deepClone(item));const cloned = {};Object.keys(obj).forEach(key => {cloned[key] = deepClone(obj[key]);});return cloned;
}

5. 对象合并和组合 API

const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { d: 5, e: 6 };// Object.assign() - 合并对象
const merged = Object.assign(target, source1, source2);
// target 被修改为 { a: 1, b: 3, c: 4, d: 5, e: 6 }// 扩展运算符合并
const merged2 = { ...target, ...source1, ...source2 };// 对象组合模式
const behavior1 = { walk() { console.log('walking'); } 
};
const behavior2 = { talk() { console.log('talking'); } 
};
const person = Object.assign({ name: 'John' }, behavior1, behavior2);

6. 原型相关 API

function Person(name) {this.name = name;
}
Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; };const john = new Person('John');// 获取原型
console.log(Object.getPrototypeOf(john) === Person.prototype); // true// 设置原型
const newProto = { sayGoodbye() { return 'Goodbye'; } };
Object.setPrototypeOf(john, newProto);// 检查原型链
console.log(john instanceof Person); // false (原型已被修改)// 创建带有指定原型的对象
const mike = Object.create(Person.prototype);
Person.call(mike, 'Mike');

7. 对象冻结和密封 API

const obj = { name: "John", age: 30 };// Object.preventExtensions() - 防止添加新属性
Object.preventExtensions(obj);
obj.city = "NY"; // 静默失败或TypeError// Object.isExtensible() - 检查是否可扩展
console.log(Object.isExtensible(obj)); // false// Object.seal() - 密封对象(不能添加/删除属性)
Object.seal(obj);
delete obj.name; // 静默失败
console.log(Object.isSealed(obj)); // true// Object.freeze() - 冻结对象(不能修改)
Object.freeze(obj);
obj.age = 31; // 静默失败
console.log(Object.isFrozen(obj)); // true

8. 对象比较和转换 API

const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
const obj3 = obj1;// 引用比较
console.log(obj1 === obj2); // false
console.log(obj1 === obj3); // true// 值比较(自定义函数)
function shallowEqual(obj1, obj2) {const keys1 = Object.keys(obj1);const keys2 = Object.keys(obj2);if (keys1.length !== keys2.length) return false;return keys1.every(key => obj1[key] === obj2[key]);
}// 对象转原始值
const obj = {value: 10,valueOf() { return this.value; },toString() { return `Object with value: ${this.value}`; }
};console.log(obj + 5); // 15 (调用 valueOf)
console.log(String(obj)); // "Object with value: 10"

9. 现代 ES6+ 对象 API

// 属性简写
const name = "John";
const age = 30;
const person = { name, age }; // { name: "John", age: 30 }// 计算属性名
const propName = "firstName";
const dynamicObj = {[propName]: "John",["last" + "Name"]: "Doe"
};// 方法简写
const obj = {// 传统方式traditional: function() { return "traditional"; },// 简写方式shorthand() { return "shorthand"; }
};// Object.hasOwn() - ES2022 (比 hasOwnProperty 更安全)
console.log(Object.hasOwn(person, 'name')); // true

10. 实用对象操作模式

对象解构

const person = { name: "John", age: 30, city: "NY" };// 基本解构
const { name, age } = person;// 重命名
const { name: personName, age: personAge } = person;// 默认值
const { name, country = "USA" } = person;// 嵌套解构
const user = { profile: { firstName: "John", address: { city: "NY" } } 
};
const { profile: { firstName, address: { city } } } = user;

对象变换

const users = [{ id: 1, name: "John", active: true },{ id: 2, name: "Jane", active: false }
];// 数组转对象映射
const usersMap = users.reduce((acc, user) => {acc[user.id] = user;return acc;
}, {});// 对象过滤
const activeUsers = Object.fromEntries(Object.entries(usersMap).filter(([id, user]) => user.active)
);// 对象映射
const userNames = Object.fromEntries(Object.entries(usersMap).map(([id, user]) => [id, user.name])
);

11. 高级对象模式

工厂模式

function createUser(name, age) {return {name,age,greet() {return `Hello, I'm ${this.name}`;}};
}

构造函数模式

function User(name, age) {this.name = name;this.age = age;
}User.prototype.greet = function() {return `Hello, I'm ${this.name}`;
};

类语法 (ES6)

class User {constructor(name, age) {this.name = name;this.age = age;}greet() {return `Hello, I'm ${this.name}`;}// 静态方法static createAnonymous() {return new User('Anonymous', 0);}
}

这些 API 覆盖了 JavaScript 对象处理的大部分场景,从基本操作到高级模式都有涉及。

http://www.dtcms.com/a/410815.html

相关文章:

  • 代码随想录算法训练营第五十二天|101.孤岛的总面积 102.沉没孤岛 103.水流问题 104.建造最大岛屿
  • 韩国优秀平面设计网站网站网址怎么写
  • 南通移动网站建设网站收录很少却有排名
  • Redis04-集群知识
  • 烟台网站制作设计如何给网站添加搜索关键字
  • AUTOSAR 状态管理(SWS_StateManagement.pdf)核心概念解析
  • AI 重构实体经济:2025 年传统产业智能化转型实践
  • 从“硬件能力比拼”到“生活价值交付”,方太智慧厨房重构行业竞争内核
  • 本地的赣州网站建设深圳做网站排名哪家专业
  • 专业建站推广网络公司网站在线留言如何做
  • commons-codec
  • Python 爬虫 HTTPS 实战,requests httpx aiohttp 抓取技巧、证书问题与抓包调试全流程
  • 网站建设小江网页设计工作室主题网站
  • 【算法部署】百度paddle环境适配
  • Linux网络:使用UDP实现网络通信(服务端客户端)
  • 免费个人网站手机app开发技术
  • 论坛网站开发demo查关键词排名软件
  • 茶吧机方案MCU控制方案开发相关资料-茶吧机单片机应用
  • 网站是如何做的好什么网站权重快
  • VR禁毒单车骑行:穿越百年禁毒史的沉浸式教育革命
  • k8s基础
  • 益阳北京网站建设网站代运营要多少费用
  • PHP使用Imagick库操作tiff
  • 海阔淘宝客助手wordpress演示站 | 紫色清新商城模板枣阳网站建设公司
  • 孤岛水流问题
  • SWAT模型在水文水资源、面源污染模拟中的实践技术应用及典型案例分析
  • 【C++】二叉搜索树的模拟实现和二叉树进阶OJ
  • Redis - Bitmap 类型
  • AUTOSAR 自适应平台 如何保证时间同步的可靠性?出现故障怎么办?
  • 设计互动网站建设做网页向网站提交数据