JavaScript 中处理 object 对象类型的常见方法

目录

  • 一、对象的基本操作
    • 1. 创建对象
    • 2. 访问和修改属性
    • 3. 添加新属性
    • 4. 删除属性
    • 5. 检查属性是否存在
  • 二、对象的组合操作
    • 1. 合并对象
    • 2. 扩展运算符
    • 3. 对象解构
  • 三、对象的深拷贝
    • 1. 使用 JSON.parse 和 JSON.stringify
    • 2. 使用递归函数
  • 四、对象的遍历
    • 1. for...in 循环
    • 2. Object.keys()
    • 3. Object.entries()
  • 五、常用对象方法
    • 1. Object.assign()
    • 2. Object.create()
    • 3. Object.freeze()
    • 4. Object.is()(严格比较)

一、对象的基本操作

1. 创建对象

使用对象字面量

const obj = { key: 'value' };

使用构造函数

const obj2 = new Object();
obj2.key = 'value';

2. 访问和修改属性

使用点操作符

const obj = { key: 'value' };
console.log(obj.key); // value

使用方括号

console.log(obj['key']); // value

修改属性值

obj.key = 'newValue';
obj['key'] = 'newValue';

3. 添加新属性

obj.newKey = 'newValue';
obj['anotherKey'] = 'anotherValue';

4. 删除属性

delete obj.key;

5. 检查属性是否存在

console.log('key' in obj); // true
console.log(obj.hasOwnProperty('key')); // true

二、对象的组合操作

1. 合并对象

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const mergedObj = Object.assign({}, obj1, obj2); // { a: 1, b: 2 }

2. 扩展运算符

const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }

3. 对象解构

const obj = { a: 1, b: 2 };
const { a, b } = obj;
console.log(a); // 1
console.log(b); // 2

三、对象的深拷贝

1. 使用 JSON.parse 和 JSON.stringify

const obj = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(obj));

注意:
这种方法不能处理 undefined、函数 和 Symbol 属性。

2. 使用递归函数

function deepCopy(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  const copy = Array.isArray(obj) ? [] : {};
  for (const key in obj) {
    copy[key] = deepCopy(obj[key]);
  }
  return copy;
}

const obj = { a: 1, b: { c: 2 } };
const deepCopy = deepCopy(obj);

四、对象的遍历

1. for…in 循环

const obj = { a: 1, b: 2 };
for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(key, obj[key]); // a 1, b 2
  }
}

2. Object.keys()

Object.keys(obj).forEach(key => {
  console.log(key, obj[key]); // a 1, b 2
});

3. Object.entries()

Object.entries(obj).forEach(([key, value]) => {
  console.log(key, value); // a 1, b 2
});

五、常用对象方法

1. Object.assign()

const obj = Object.assign({ a: 1 }, { b: 2 }, { c: 3 }); // { a: 1, b: 2, c: 3 }

2. Object.create()

const obj = Object.create({ a: 1 });
console.log(obj.a); // 1

3. Object.freeze()

Object.freeze(obj);
obj.a = 2; // 不会报错,但不会修改对象

4. Object.is()(严格比较)

Object.is('foo', 'foo'); // true
Object.is({}, {}); // false

你可能感兴趣的:(前端,js,javascript,前端,typescript)