JavaScript의 주요 객체 메소드 이해

Mary-Kate Olsen
풀어 주다: 2024-10-18 12:53:04
원래의
513명이 탐색했습니다.

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
로그인 후 복사

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)
로그인 후 복사

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

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));  // Output: ['a', 'b', 'c']
로그인 후 복사

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

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));  // Output: [1, 2, 3]
로그인 후 복사

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

const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj));  // Output: [['a', 1], ['b', 2], ['c', 3]]
로그인 후 복사

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
로그인 후 복사

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

const obj = { a: 1 };
Object.seal(obj);
obj.a = 2;  // Allowed
delete obj.a;  // Not allowed
console.log(obj.a);  // Output: 2
로그인 후 복사

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

const obj = { a: 1 };
Object.preventExtensions(obj);
obj.b = 2;  // Not allowed
console.log(obj.b);  // Output: undefined
로그인 후 복사

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

const obj = {};
const proto = Object.getPrototypeOf(obj);
console.log(proto);  // Output: {} (the default Object prototype)
로그인 후 복사

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

const proto = { greet() { console.log('Hello!'); } };
const obj = {};
Object.setPrototypeOf(obj, proto);
obj.greet();  // Output: 'Hello!'
로그인 후 복사

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
로그인 후 복사

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
로그인 후 복사

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

const obj = { a: 1 };
const descriptor = Object.getOwnPropertyDescriptor(obj, 'a');
console.log(descriptor);  
// Output: { value: 1, writable: true, enumerable: true, configurable: true }
로그인 후 복사

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

const obj = { a: 1 };
const descriptors = Object.getOwnPropertyDescriptors(obj);
console.log(descriptors);
// Output: { a: { value: 1, writable: true, enumerable: true, configurable: true } }
로그인 후 복사

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

const obj = { a: 1 };
Object.defineProperty(obj, 'b', { value: 2, enumerable: false });
console.log(Object.getOwnPropertyNames(obj));  // Output: ['a', 'b']
로그인 후 복사

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

console.log(Object.is(NaN, NaN));  // Output: true
console.log(Object.is(+0, -0));    // Output: false
로그인 후 복사

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

const obj = Object.freeze({ a: 1 });
console.log(Object.isFrozen(obj));  // Output: true
로그인 후 복사

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

const obj = Object.seal({ a: 1 });
console.log(Object.isSealed(obj));  // Output: true
로그인 후 복사

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

const obj = { a: 1 };
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj));  // Output: false
로그인 후 복사

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

const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj);  // Output: { a: 1, b: 2 }
로그인 후 복사

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

const obj = { a: 1 };
console.log(obj.hasOwnProperty('a'));  // Output: true
로그인 후 복사

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
로그인 후 복사

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 }
  ]
}
*/

로그인 후 복사

위 내용은 JavaScript의 주요 객체 메소드 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!