From 3670c252cd1698327a84c3bd288e8bc83117fc7e Mon Sep 17 00:00:00 2001 From: 윤승재 Date: Thu, 1 Jul 2021 16:03:21 +0900 Subject: Object.keys, Object.getOwnPropertyNames 문서 추가 (#1297) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: echo.youn Co-authored-by: Sungwoo Park --- .../object/getownpropertynames/index.html | 151 ++++++++++++++++++++ .../global_objects/object/keys/index.html | 158 +++++++++++++++++++++ 2 files changed, 309 insertions(+) create mode 100644 files/ko/web/javascript/reference/global_objects/object/getownpropertynames/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/keys/index.html (limited to 'files') diff --git a/files/ko/web/javascript/reference/global_objects/object/getownpropertynames/index.html b/files/ko/web/javascript/reference/global_objects/object/getownpropertynames/index.html new file mode 100644 index 0000000000..46338a2c8a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/getownpropertynames/index.html @@ -0,0 +1,151 @@ +--- +title: Object.getOwnPropertyNames() +slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames +tags: + - ECMAScript 5 + - JavaScript + - JavaScript 1.8.5 + - Method + - Object + - Reference + - Polyfill +browser-compat: javascript.builtins.Object.getOwnPropertyNames +--- +
{{JSRef}}
+ +

Object.getOwnPropertyNames() 메서드는 전달된 객체의 모든 속성 (심볼을 사용하는 속성을 제외한 열거할 수 없는 속성 포함) 들을 배열로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/object-getownpropertynames.html")}}
+ +

구문

+ +
Object.getOwnPropertyNames(obj)
+ +

매개변수

+ +
+
obj
+
반환 받을 열거형 속성과 열거형이 아닌 속성을 가진 객체
+
+ +

반환 값

+ +

전달된 객체에 있는 속성들의 문자열 배열을 반환합니다.

+ +

설명

+ +

Object.getOwnPropertyNames() 는 전달된 객체(obj)의 열거형 및 열거할 수 없는 속성들을 문자열 배열로 반환합니다. + 배열의 열거할 수 있는 속성들의 순서는 {{jsxref("Statements/for...in", "for...in")}} 반복문 (또는 {{jsxref("Object.keys()")}})이 처리되는 순서와 일치합니다. + ES6 문법에 따라, 객체의 정수형 키 (열거형 및 비-열거형 포함)가 먼저 배열에 오름차순으로 추가된 다음 문자열 키를 삽입하는 순서로 추가됩니다.

+

ES5에서는 인수(obj)가 객체가 아닌 경우 (원시 타입) {{jsxref("TypeError")}} 가 발생합니다. +ES2015에서는, 객체가 아닌 인수를 객체 타입으로 강제 형변환합니다. +

+ +
Object.getOwnPropertyNames('foo');
+// TypeError: "foo" is not an object (ES5 code)
+
+Object.getOwnPropertyNames('foo');
+// ["0", "1", "2", "length"]  (ES2015 code)
+
+ +

예시

+ +

Using Object.getOwnPropertyNames()

+ +
var arr = ['a', 'b', 'c'];
+console.log(Object.getOwnPropertyNames(arr).sort()); // .sort() 는 배열 메서드입니다.
+// logs ["0", "1", "2", "length"]
+
+// 배열형 객체
+var obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.getOwnPropertyNames(obj).sort()); // .sort() 는 배열 메서드입니다.
+// logs ["0", "1", "2"]
+
+// 속성 명과 속성 값을 Array.forEach 메서드를 사용하여 로깅합니다.
+Object.getOwnPropertyNames(obj).forEach(
+  function (val, idx, array) {
+    console.log(val + ' -> ' + obj[val]);
+  }
+);
+// logs
+// 0 -> a
+// 1 -> b
+// 2 -> c
+
+// 열거할 수 없는 속성
+var my_obj = Object.create({}, {
+  getFoo: {
+    value: function() { return this.foo; },
+    enumerable: false
+  }
+});
+my_obj.foo = 1;
+
+console.log(Object.getOwnPropertyNames(my_obj).sort());
+// logs ["foo", "getFoo"]
+
+ +

만약 열거 가능한 속성만 사용한다면, {{jsxref("Object.keys()")}} 또는 {{jsxref("Statements/for...in", "for...in")}} 반복문을 사용하는걸 권장합니다. + (이는 객체의 프로토타입 체인을 먼저 사용하여 열거 가능한 속성을 반환합니다. 단, 후자는{{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}}에 필터 됩니다.) +

+ +

프로토타입 체인에 있는 요소들은 나열되지 않음:

+ +
function ParentClass() {}
+ParentClass.prototype.inheritedMethod = function() {};
+
+function ChildClass() {
+  this.prop = 5;
+  this.method = function() {};
+}
+ChildClass.prototype = new ParentClass;
+ChildClass.prototype.prototypeMethod = function() {};
+
+console.log(
+  Object.getOwnPropertyNames(
+    new ChildClass() // ["prop", "method"]
+  )
+);
+
+ +

열거할 수 없는 속성만 가져오기

+ +

이 방법은 {{jsxref("Array.prototype.filter()")}} 함수를 사용해 (Object.getOwnPropertyNames() 을 통해 얻은) 모든 키 중 ({{jsxref("Object.keys()")}} 을 통해 얻은) 열거 가능한 키들을 제거하여 열거할 수 없는 키들만 출력합니다.

+ +
var target = myObject;
+var enum_and_nonenum = Object.getOwnPropertyNames(target);
+var enum_only = Object.keys(target);
+var nonenum_only = enum_and_nonenum.filter(function(key) {
+  var indexInEnum = enum_only.indexOf(key);
+  if (indexInEnum == -1) {
+    // enum_only 에 키 값이 없다는 것은
+    // 그 키가 열거할 수 없는 키 임을 의미합니다.
+    // 그래서 이 필터에서 true를 반환합니다.
+    return true;
+  } else {
+    return false;
+  }
+});
+
+console.log(nonenum_only);
+
+ +

명세

+ +{{Specifications}} + +

브라우저 호환성

+ +

{{Compat}}

+ +

같이 보기

+ +
    +
  • Object.getOwnPropertyNames 의 폴리필 코드는 아래에서 확인 할 수 있습니다. core-js
  • +
  • Enumerability and ownership of properties
  • +
  • {{jsxref("Object.prototype.hasOwnProperty()")}}
  • +
  • {{jsxref("Object.prototype.propertyIsEnumerable()")}}
  • +
  • {{jsxref("Object.create()")}}
  • +
  • {{jsxref("Object.keys()")}}
  • +
  • {{jsxref("Array.forEach()")}}
  • +
diff --git a/files/ko/web/javascript/reference/global_objects/object/keys/index.html b/files/ko/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..0854f9037a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,158 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Reference/Global_Objects/Object/keys +tags: + - ECMAScript 5 + - JavaScript + - JavaScript 1.8.5 + - Method + - Object + - Polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +browser-compat: javascript.builtins.Object.keys +--- +
{{JSRef}}
+ +

Object.keys() 메소드는 주어진 객체의 속성 이름들을 일반적인 반복문과 + 동일한 순서로 순회되는 열거할 수 있는 배열로 반환합니다. +

+ +
{{EmbedInteractiveExample("pages/js/object-keys.html")}}
+ + +

구문

+ +
Object.keys(obj)
+ +

매개변수

+ +
+
obj
+
열거할 수 있는 속성 이름들을 반환 받을 객체
+
+ +

반환 값

+ +

전달된 객체의 열거할 수 있는 모든 속성 이름들을 나타내는 문자열 배열 +

+ +

설명

+ +

Object.keys() 는 전달된 객체에서 직접 찾은 열거할 수 있는 속성 이름에 해당하는 문자열 배열을 반환합니다. + 속성 이름의 순서는 객체의 속성을 수동으로 반복하여 지정하는 것과 동일합니다.

+ +

예시

+ +

Using Object.keys

+ +
// 단순 배열
+const arr = ['a', 'b', 'c'];
+console.log(Object.keys(arr)); // console: ['0', '1', '2']
+
+// 배열형 객체
+const obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.keys(obj)); // console: ['0', '1', '2']
+
+// 키와 순서가 무작위인 배열형 객체
+const anObj = { 100: 'a', 2: 'b', 7: 'c' };
+console.log(Object.keys(anObj)); // console: ['2', '7', '100']
+
+// getFoo 는 열거할 수 없는 속성입니다.
+const myObj = Object.create({}, {
+  getFoo: {
+    value: function () { return this.foo; }
+  }
+});
+myObj.foo = 1;
+console.log(Object.keys(myObj)); // console: ['foo']
+
+ +

만약 열거할 수 없는 속성도 포함한 속성 이름들을 원한다면, 다음을 참고할 수 있습니다. + {{jsxref("Object.getOwnPropertyNames()")}}.

+ +

비객체 강제 형변환

+ +

ES5에서, 이 메서드의 인수에 비객체(원시형)을 전달할 경우, {{jsxref("TypeError")}}가 발생합니다.

+ +

ES2015부터는 객체가 아닌 인수는 객체로 강제 변환됩니다.

+ +
// ES5
+Object.keys('foo');  // TypeError: "foo" is not an object
+
+// ES2015+
+Object.keys('foo');  // ["0", "1", "2"]
+
+ +

폴리필

+ +

Object.keys를 지원하지 않는 환경에서 사용하시려면 다음 스니펫을 복사하십시오.

+ +
// From https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
+if (!Object.keys) {
+  Object.keys = (function() {
+    'use strict';
+    var hasOwnProperty = Object.prototype.hasOwnProperty,
+        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
+        dontEnums = [
+          'toString',
+          'toLocaleString',
+          'valueOf',
+          'hasOwnProperty',
+          'isPrototypeOf',
+          'propertyIsEnumerable',
+          'constructor'
+        ],
+        dontEnumsLength = dontEnums.length;
+
+    return function(obj) {
+      if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) {
+        throw new TypeError('Object.keys called on non-object');
+      }
+
+      var result = [], prop, i;
+
+      for (prop in obj) {
+        if (hasOwnProperty.call(obj, prop)) {
+          result.push(prop);
+        }
+      }
+
+      if (hasDontEnumBug) {
+        for (i = 0; i < dontEnumsLength; i++) {
+          if (hasOwnProperty.call(obj, dontEnums[i])) {
+            result.push(dontEnums[i]);
+          }
+        }
+      }
+      return result;
+    };
+  }());
+}
+
+ +

위의 코드에는 다른 창에서 객체를 전달했을 때 IE7 (그리고 아마 IE8)에서는 열거할 수 없는 키가 포함되어 있습니다.

+ +

간단한 브라우저 폴리필은 다음을 참고하세요. Javascript - Object.keys Browser Compatibility.

+ +

명세

+ +{{Specifications}} + +

브라우저 호환성

+ + +

{{Compat}}

+ +

같이 보기

+ +
    +
  • Object.keys 의 폴리필 코드는 아래에서 확인할 수 있습니다. core-js
  • +
  • Enumerability + and ownership of properties
  • +
  • {{jsxref("Object.prototype.propertyIsEnumerable()")}}
  • +
  • {{jsxref("Object.create()")}}
  • +
  • {{jsxref("Object.getOwnPropertyNames()")}}
  • +
  • {{jsxref("Object.values()")}}
  • +
  • {{jsxref("Object.entries()")}}
  • +
-- cgit v1.2.3-54-g00ecf