IT박스

열거 가능한 것은 무엇을 의미합니까?

itboxs 2020. 6. 23. 07:58

열거 가능한 것은 무엇을 의미합니까?


MDN의 for..in 페이지 에서 "for..in은 객체의 열거 가능한 속성을 반복합니다."라고 말했습니다.

그런 다음 "Enumerable properties는 for..in 루프에 의해 반복 될 수있는 속성입니다."라는 속성열거 및 소유권 페이지로 이동했습니다.

사전은 열거 가능한 것을 계산 가능한 것으로 정의하지만 그 의미를 실제로 시각화 할 수는 없습니다. 열거 가능한 것의 예를 얻을 수 있습니까?


열거 가능한 속성은 for..in루프 중에 포함되거나 방문 할 수있는 속성입니다 (또는와 같은 유사한 속성 반복 Object.keys()).

속성이 열거 가능한 것으로 식별되지 않으면 루프는 객체 내에 있음을 무시합니다.

var obj = { key: 'val' };

console.log('toString' in obj); // true
console.log(typeof obj.toString); // "function"

for (var key in obj)
    console.log(key); // "key"

속성은 자체 [[Enumerable]]속성 으로 열거 가능하거나 그렇지 않은 것으로 식별됩니다 . 이것을 속성 설명 자의 일부로 볼 수 있습니다 .

var descriptor = Object.getOwnPropertyDescriptor({ bar: 1 }, 'bar');

console.log(descriptor.enumerable); // true
console.log(descriptor.value);      // 1

console.log(descriptor);
// { value: 1, writable: true, enumerable: true, configurable: true }

for..in루프는 객체의 속성 이름을 반복.

var foo = { bar: 1, baz: 2};

for (var prop in foo)
    console.log(prop); // outputs 'bar' and 'baz'

그러나이 속성은 console.log(prop);속성 인 [[Enumerable]]속성에 대한 명령문 만 평가합니다 ( 이 경우 ) true.

이 조건은 객체 가 더 많은 속성 , 특히 상속을 가지기 때문에 적용됩니다 .

console.log(Object.getOwnPropertyNames(Object.prototype));
// ["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", /* etc. */]

이러한 각 속성은 여전히 객체에 존재합니다 .

console.log('constructor' in foo); // true
console.log('toString' in foo);    // true
// etc.

그러나 for..in열거 할 수 없기 때문에 루프에서 건너 뜁니다 .

var descriptor = Object.getOwnPropertyDescriptor(Object.prototype, 'constructor');

console.log(descriptor.enumerable); // false

객체를 통해 객체를 만들면 myObj = {foo: 'bar'}모든 속성을 열거 할 수 있습니다. 따라서 더 쉬운 질문은 열거 할 수없는 것입니다. 특정 객체에는 열거 할 수없는 속성이 있습니다. 예를 들어 Object.getOwnPropertyNames([])([]에서 열거 할 수 있거나없는 모든 속성의 배열을 반환하는) 호출 하면 배열의 열거 ['length']할 수없는 속성 인 'length'가 포함 된 을 반환합니다 . .

다음을 호출하여 열거 할 수없는 고유 한 속성을 만들 수 있습니다 Object.defineProperty.

var person = { age: 18 };
Object.defineProperty(person, 'name', { value: 'Joshua', enumerable: false });

person.name; // 'Joshua'
for (prop in person) {
  console.log(prop);
}; // 'age'

이 예제 는 JavaScript의 열거 불가능한 속성을 많이 사용 하지만 열거 된 객체를 보여줍니다. 속성은 쓰기 가능, 구성 가능 또는 열거 가능할 수 있습니다. John Resig는 ECMAScript 5 Objects and Properties 범위에서 이에 대해 설명합니다 .

그리고 왜 속성을 열거 불가능하게 만들고 싶어하는지 에 대한 스택 오버플로 질문이 있습니다 .


시각화해야 할 것보다 훨씬 지루합니다.

문자 그대로 "enumerable"이라는 모든 속성에 속성이 있습니다. false로 설정되면 for..in메소드는 해당 특성을 건너 뛰고 존재하지 않는 척합니다.

"valueOf"및 "hasOwnProperty"와 같이 "enumerable"이 false로 설정된 객체에는 많은 속성이 있습니다. 왜냐하면 JavaScript 엔진이이를 반복하는 것을 원하지 않기 때문입니다.

다음 Object.defineProperty방법을 사용하여 열거 할 수없는 고유 한 속성을 만들 수 있습니다 .

  var car = {
    make: 'Honda',
    model: 'Civic',
    year: '2008',
    condition: 'bad',
    mileage: 36000
  };

  Object.defineProperty(car, 'mySecretAboutTheCar', {
    value: 'cat pee in back seat',
    enumerable: false
  });

Now, the fact that there is even a secret about the car is hidden. Of course they can still access the property directly and get the answer:

console.log(car.mySecretAboutTheCar); // prints 'cat pee in back seat'

But, they would have to know that the property exists first, because if they're trying to access it through for..in or Object.keys it will remain completely secret:

console.log(Object.keys(car)); //prints ['make', 'model', 'year', 'condition', 'mileage']

They should have just called it, "forInAble."


If you're having difficulty visualising "what does it mean to be enumerable?" why not ask yourself, what does it mean to be nonenumerable?

I think of it a bit like this, a nonenumerable property exists but is partially hidden; meaning that nonenumerable is the weird one. Now you can imagine enumerable as what is left - the more natural property we're used to encountering since we discovered Objects. Consider

var o = {};
o['foo'] =  0;                               // enumerable, normal
Object.defineProperty(o, 'bar', {value: 1}); // nonenumerable, weird

Now in a for..in, imagine it like pseudocode

for property in o:
    if not property enumerable continue // skip non-enumerable, "bar"
    else do /* whatever */              // act upon enumerable, "foo"

where the body of the loop you typed in JavaScript is in the place of /* whatever */


I will write one line definition of ENUMERABLE

Enumerable: Specifies whether the property can be returned in a for/in loop.

var obj = {};
Object.defineProperties(data, {
    set1: {enumerable: true},
    set2: {enumerable: false},
});
Object.keys(obj); // ["set1"]
Object.getOwnPropertyNames(obj); // ["set1", "set2"]

methods are not enumerable; or rather built in methods are not.. tho after searching on what enumerable means to java script; it just refers to a property attribute.. all created objects in ecma3 are enumerable, and ecma5 u can now define it....that's it.. :D lol took me a bit to find the answer; but I believe its talked about in David Flanagan's book.. so I guess it means "hidden", or not "hidden" in that methods are not shown in the for in loop, and thus are "hidden"

참고URL : https://stackoverflow.com/questions/17893718/what-does-enumerable-mean