Memahami Kaedah Objek Utama dalam JavaScript

Mary-Kate Olsen
Lepaskan: 2024-10-18 12:53:04
asal
517 orang telah melayarinya

Understanding Key Object Methods in JavaScript

JavaScript 的物件包含許多有用的方法,可以幫助開發人員輕鬆操作物件。讓我們透過簡短的解釋和範例來了解一些最重要的內容

  1. Object.create()
  2. Object.assign()
  3. Object.keys()
  4. Object.values()
  5. Object.entries()
  6. Object.freeze()
  7. Object.seal()
  8. Object.preventExtensions()
  9. Object.getPrototypeOf()
  10. Object.setPrototypeOf()
  11. Object.defineProperty()
  12. Object.defineProperties()
  13. Object.getOwnPropertyDescriptor()
  14. Object.getOwnPropertyDescriptors()
  15. Object.getOwnPropertyNames()
  16. Object.is()
  17. Object.isFrozen()
  18. Object.isSealed()
  19. Object.isExtensible()
  20. Object.fromEntries()
  21. Object.hasOwnProperty()
  22. Object.hasOwn()
  23. Object.groupBy()(建議的功能,可能不完全可用)

Object.create()
Object.create() 是 JavaScript 中的一個方法,用於建立具有指定原型物件和可選屬性的新物件。與使用物件文字或建構函數相比,它允許對物件的原型和屬性進行更細粒度的控制。

const personPrototype = {
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const john = Object.create(personPrototype);
john.name = "John";
john.greet();  // Output: Hello, my name is John
Salin selepas log masuk

Object.assign()
Object.assign() 是一種內建 JavaScript 方法,用於將所有可列舉自身屬性的值從一個或多個來源物件複製到目標物件。它執行淺複製並傳回修改後的目標物件。

const target = { a: 1 };
const source = { b: 2, c: 3 };
const result = Object.assign(target, source);
console.log(result);  // Output: { a: 1, b: 2, c: 3 }
console.log(target);  // Output: { a: 1, b: 2, c: 3 } (target is also modified)
Salin selepas log masuk

Object.keys()
傳回物件自己的可枚舉屬性名稱(鍵)的陣列

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));  // Output: ['a', 'b', 'c']
Salin selepas log masuk

Object.values()
傳回物件本身可枚舉屬性值的陣列

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));  // Output: [1, 2, 3]
Salin selepas log masuk

Object.entries()
傳回物件本身可枚舉屬性 [key, value] 對的陣列

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj));  // Output: [['a', 1], ['b', 2], ['c', 3]]
Salin selepas log masuk

Object.freeze()
凍結對象,防止新增屬性或變更或刪除現有屬性

const obj = { a: 1 };
Object.freeze(obj);
obj.a = 2;  // No effect, because the object is frozen
console.log(obj.a);  // Output: 1
Salin selepas log masuk

Object.seal()
密封對象,防止添加新屬性,但允許修改現有屬性。

const obj = { a: 1 };
Object.seal(obj);
obj.a = 2;  // Allowed
delete obj.a;  // Not allowed
console.log(obj.a);  // Output: 2
Salin selepas log masuk

Object.preventExtensions()
防止將任何新屬性新增至對象,但允許修改和刪除現有屬性

const obj = { a: 1 };
Object.preventExtensions(obj);
obj.b = 2;  // Not allowed
console.log(obj.b);  // Output: undefined
Salin selepas log masuk

Object.getPrototypeOf()
傳回指定物件
的原型(即內部[[Prototype]])

const obj = {};
const proto = Object.getPrototypeOf(obj);
console.log(proto);  // Output: {} (the default Object prototype)
Salin selepas log masuk

Object.setPrototypeOf()
設定指定物件的原型。

const proto = { greet() { console.log('Hello!'); } };
const obj = {};
Object.setPrototypeOf(obj, proto);
obj.greet();  // Output: 'Hello!'
Salin selepas log masuk

Object.defineProperty()
在物件上定義一個新屬性或修改現有屬性,並使用屬性描述符的附加選項(例如,可寫入、可配置)。

const obj = {};
Object.defineProperty(obj, 'a', {
  value: 42,
  writable: false,  // Cannot modify the value
});
obj.a = 100;  // No effect because writable is false
console.log(obj.a);  // Output: 42
Salin selepas log masuk

Object.defineProperties()
使用屬性描述符在物件上定義多個屬性。

const obj = {};
Object.defineProperties(obj, {
  a: { value: 42, writable: false },
  b: { value: 100, writable: true }
});
console.log(obj.a);  // Output: 42
console.log(obj.b);  // Output: 100
Salin selepas log masuk

Object.getOwnPropertyDescriptor()
傳回物件屬性的描述符。

const obj = { a: 1 };
const descriptor = Object.getOwnPropertyDescriptor(obj, 'a');
console.log(descriptor);  
// Output: { value: 1, writable: true, enumerable: true, configurable: true }
Salin selepas log masuk

Object.getOwnPropertyDescriptors()
傳回一個對象,其中包含對象自身屬性的所有屬性描述符

const obj = { a: 1 };
const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
// Output: { a: { value: 1, writable: true, enumerable: true, configurable: true } }
Salin selepas log masuk

Object.getOwnPropertyNames()
傳回直接在物件上找到的所有屬性(包括不可列舉的屬性)的陣列。

const obj = { a: 1 };
Object.defineProperty(obj, 'b', { value: 2, enumerable: false });
console.log(Object.getOwnPropertyNames(obj));  // Output: ['a', 'b']
Salin selepas log masuk

Object.is()
比較兩個值是否相同(如 === 但處理 NaN 等特殊情況)

console.log(Object.is(NaN, NaN));  // Output: true
console.log(Object.is(+0, -0));    // Output: false
Salin selepas log masuk

Object.isFrozen()
檢查物件是否被凍結

const obj = Object.freeze({ a: 1 });
console.log(Object.isFrozen(obj));  // Output: true
Salin selepas log masuk

Object.isSealed()
檢查物體是否被密封。

const obj = Object.seal({ a: 1 });
console.log(Object.isSealed(obj));  // Output: true
Salin selepas log masuk

Object.isExtensible()
檢查是否可以將新屬性新增到物件。

const obj = { a: 1 };
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj));  // Output: false
Salin selepas log masuk

Object.fromEntries()
將鍵值對數組轉換為物件

const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj);  // Output: { a: 1, b: 2 }
Salin selepas log masuk

Object.hasOwnProperty()
檢查物件是否擁有指定的屬性(不是繼承的)

const obj = { a: 1 };
console.log(obj.hasOwnProperty('a'));  // Output: true
Salin selepas log masuk

Object.hasOwn()
Object.hasOwn() 是 ES2022 中引入的較新方法,作為 Object.hasOwnProperty() 的替代方法。它檢查一個物件是否具有帶有指定鍵的直接(自己)屬性,而無需查找原型鏈。

const obj = {
  name: 'Alice',
  age: 25
};

console.log(Object.hasOwn(obj, 'name'));  // true
console.log(Object.hasOwn(obj, 'gender'));  // false
Salin selepas log masuk

Object.groupBy
Object.groupBy is a relatively new feature proposed for JavaScript in ECMAScript 2024 that allows you to group objects based on a common criterion. It is not yet widely available across all environments, so it may not work in many browsers or JavaScript engines until fully implemented.

const array = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 },
];

// Group objects by age
const groupedByAge = Object.groupBy(array, item => item.age);

console.log(groupedByAge);

/*
Expected Output:
{
  25: [
    { name: 'Alice', age: 25 },
    { name: 'Charlie', age: 25 }
  ],
  30: [
    { name: 'Bob', age: 30 },
    { name: 'David', age: 30 }
  ]
}
*/

Salin selepas log masuk

Atas ialah kandungan terperinci Memahami Kaedah Objek Utama dalam JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!