創建對象
//使用對象字面量、構造函數或者Object.create()方法來創建對象// 對象字面量
const person = {name: 'John',age: 30,hobbies: ['reading', 'swimming']
};// 構造函數
function Car(make, model) {this.make = make;this.model = model;
}
const myCar = new Car('Toyota', 'Corolla');// Object.create()
const animal = {speak() {console.log(`${this.name} makes a noise.`);}
};
const dog = Object.create(animal);
dog.name = 'Buddy';
?
訪問屬性
//訪問對象屬性有兩種方式,分別是點號表示法和方括號表示法
console.log(person.name); // 'John'
console.log(person['age']); // 30// 動態訪問
const key = 'hobbies';
console.log(person[key]); // ['reading', 'swimming']
?
修改和添加屬性
//可以直接通過賦值來修改或添加對象的屬性。person.age = 31; // 修改現有屬性
person.city = 'New York'; // 添加新屬性
person['isStudent'] = false; // 方括號表示法添加屬性
?
刪除屬性
//使用delete操作符能夠刪除對象的屬性。delete person.hobbies; // 刪除hobbies屬性
console.log(person.hobbies); // undefined
?
檢查屬性是否存在
//in操作符和hasOwnProperty()方法可以檢查對象是否擁有某個屬性console.log('name' in person); // true
console.log(person.hasOwnProperty('city')); // true
?
遍歷對象
//使用for...in循環、Object.keys()、Object.values()和Object.entries()來遍歷對象// for...in循環
for (const key in person) {console.log(key, person[key]);
}// Object.keys() - 獲取所有鍵
console.log(Object.keys(person)); // ['name', 'age', 'city', 'isStudent']// Object.values() - 獲取所有值
console.log(Object.values(person)); // ['John', 31, 'New York', false]// Object.entries() - 獲取所有鍵值對
console.log(Object.entries(person));
// [['name', 'John'], ['age', 31], ['city', 'New York'], ['isStudent', false]]
??
凍結對象
//Object.freeze()可以阻止修改對象的屬性const frozen = Object.freeze({ x: 5 });
frozen.x = 10; // 操作被忽略(嚴格模式下會報錯)
console.log(frozen.x); // 5
?
密封對象
//Object.seal()允許修改現有屬性,但不能添加或刪除屬性。const sealed = Object.seal({ y: 10 });
sealed.y = 20; // 可以修改
sealed.z = 30; // 無效(嚴格模式下會報錯)
delete sealed.y; // 無效
?
嵌套對象
//對于嵌套對象,可以鏈式訪問和修改屬性const user = {profile: {address: {city: 'London'}}
};console.log(user.profile.address.city); // 'London'
user.profile.address.zip = 'SW1A 1AA'; // 添加嵌套屬性
?
對象方法
//對象的屬性值也可以是函數,這樣的屬性被稱為方法const calculator = {add(a, b) {return a + b;},subtract(a, b) {return a - b;}
};console.log(calculator.add(5, 3)); // 8
?
this關鍵字
//在對象方法內部,this指向調用該方法的對象const person = {name: 'Alice',greet() {console.log(`Hello, ${this.name}!`);}
};person.greet(); // 'Hello, Alice!'
?
對象的鍵與值
let obj = { "id": "1", "name": "millia", "color": "red"}/* Object.keys() */
/* 返回一個包含 javascript 對象鍵的數組如果鍵是數字,Object.keys() 函數將按排序順序返回數字鍵的數組,鍵值仍將保持與原始 javascript 對象相同的值映射*/
console.log(Object.keys(obj))
//["id", "name", "color"]/* Object.entries() */
/* 將整個對象拆分為小數組。每個數組由 [key, value] 形式的鍵值對組成*/
console.log(Object.entries(obj))
//0: (2) ['id', '1']
//1: (2) ['name', 'millia']
//2: (2) ['color', 'red']console.log(JSON.stringify(Object.entries(obj)))
//[["id","1"],["name","millia"],["color","red"]]for (const [key, value] of Object.entries(obj)) {console.log(`${key}: ${value}`);
}
//id: 1
//name: millia
//color: red/*for 循環*/
for(let i in obj) {console.log(i) // 鍵console.log(obj[i]) //值
}
// id
// 1
// name
// millia
// color
// red/* Object.values() */
/* 靜態方法返回一個給定對象的自有可枚舉字符串鍵屬性值組成的數組 */
console.log(Object.values(obj))
//['1', 'millia', 'red']
?
對象的合并
/* Object.assign(target,...sources) */
/* target 需要應用源對象屬性的目標對象,修改后將作為返回值sources 一個或多個包含要應用的屬性的源對象注意target對象有值還是空值{} */
let target = { a: 1, b: 2 }
let source = { b: 4, c: 5 }
console.log(Object.assign({},target, source),target,source)
//{a: 1, b: 4, c: 5} {a: 1, b: 2} {b: 4, c: 5}
console.log(target,Object.assign(target, source))
//{a: 1, b: 4, c: 5} {a: 1, b: 4, c: 5}/* 展開運算符... 解構賦值 */
/* 可以在函數調用/數組構造時,將數組表達式或者 string 在語法層面展開;還可以在構造字面量對象時,將對象表達式按 key-value 的方式展開。(注: 字面量一般指 [1, 2, 3] 或者 {name: "mdn"} 這種簡潔的構造方式) 函數調用:myFunction(...iterableObj)字面量數組構造或字符串:[...iterableObj, '4', ...'hello', 6]構造字面量對象,進行克隆或者屬性拷貝:let objClone = { ...obj }
*/
const obj1 = { a: 1, b: 2 }
const obj2 = { b: 3, c: 4 }
const obj3 = { ...obj1, ...obj2 }
console.log(obj3)
// { a: 1, b: 3, c: 4 }
?
對象的去重
//基于單個屬性去重使用Array.reduce()或者Map來實現
const people = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' },{ id: 1, name: 'Charlie' } // 重復id
];// 使用Map
const uniqueById = [...new Map(people.map(person => [person.id, person])).values()];
console.log(uniqueById); // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]// 等效方法(使用reduce)
const uniqueById2 = people.reduce((acc, current) => {const x = acc.find(item => item.id === current.id);if (!x) {return acc.concat([current]);} else {return acc;}
}, []);//深度比較對象去重,當需要比較對象的所有屬性是否都相同時,可以使用JSON.stringify()或者自定義比較函數。不過要注意,JSON.stringify()有局限性,比如它無法處理函數、undefined或者循環引用的情況。
const users = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' },{ name: 'Alice', id: 1 } // 屬性順序不同,但內容相同
];// 使用JSON.stringify()(簡單但有局限性)
const uniqueByStringify = [...new Set(users.map(user => JSON.stringify(user)))].map(str => JSON.parse(str));
console.log(uniqueByStringify); // 去重成功// 自定義深度比較函數
function isEqual(obj1, obj2) {if (obj1 === obj2) return true;if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) return false;const keys1 = Object.keys(obj1);const keys2 = Object.keys(obj2);if (keys1.length !== keys2.length) return false;for (const key of keys1) {if (!obj2.hasOwnProperty(key) || !isEqual(obj1[key], obj2[key])) return false;}return true;
}const uniqueByDeepCompare = users.filter((current, index, self) => self.findIndex(item => isEqual(item, current)) === index
);//處理嵌套對象,如果對象包含嵌套結構,去重會更復雜一些,需要遞歸比較所有層級的屬性。
const items = [{ id: 1, details: { age: 30 } },{ id: 2, details: { age: 25 } },{ id: 1, details: { age: 30 } } // 完全重復
];// 自定義深度比較(支持嵌套對象)
function deepCompare(obj1, obj2) {if (obj1 === obj2) return true;if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) return false;const keys1 = Object.keys(obj1);const keys2 = Object.keys(obj2);if (keys1.length !== keys2.length) return false;for (const key of keys1) {if (obj1[key] instanceof Date && obj2[key] instanceof Date) {if (obj1[key].getTime() !== obj2[key].getTime()) return false;} else if (!deepCompare(obj1[key], obj2[key])) {return false;}}return true;
}const uniqueItems = items.filter((current, index, self) => self.findIndex(item => deepCompare(item, current)) === index
);//基于多個屬性去重,當需要根據對象的多個屬性組合來判斷是否重復時,可以這樣實現。
const products = [{ name: 'Apple', category: 'Fruit' },{ name: 'Banana', category: 'Fruit' },{ name: 'Apple', category: 'Fruit' } // 重復組合
];const uniqueProducts = products.reduce((acc, current) => {const key = `${current.name}-${current.category}`;const isDuplicate = acc.some(item => `${item.name}-${item.category}` === key);if (!isDuplicate) {acc.push(current);}return acc;
}, []);
去重方法選擇建議
- 基于單個屬性去重:推薦使用Map,因為它的時間復雜度是 O (n),效率較高。
- 深度比較去重:如果對象結構簡單,可以使用JSON.stringify();如果對象結構復雜,建議使用自定義比較函數或者 Lodash。
- 性能考慮:對于大型數組,使用
Map
或者Set
的方法性能更好,因為它們的查找效率比Array.find()更高。