javascript 可枚举是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17893718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:01:05  来源:igfitidea点击:

What does enumerable mean?

javascriptenumerable

提问by Patrick

I was directed to MDN's for..in pagewhen it said, "for..in Iterates over the enumerable properties of an object."

当它说“for..in 迭代对象的可枚举属性”时,我被定向到 MDN 的for..in 页面

Then I went to the Enumerability and ownership of properties pagewhere it said "Enumerable properties are those which can be iterated by a for..in loop."

然后我转到属性可枚举性和所有权页面,它说“可枚举属性是那些可以通过 for..in 循环迭代的属性”。

The dictionary defines enumerable as countable, but I can't really visualize what that means. Could i get an example of something being enumerable?

字典将 enumerable 定义为可数,但我无法想象这意味着什么。我能得到一个可枚举的例子吗?

回答by Jonathan Lonowski

An enumerable property is one that can be included in and visited during for..inloops (or a similar iteration of properties, like Object.keys()).

可枚举属性是可以在for..in循环中包含和访问的属性(或类似的属性迭代,如Object.keys())。

If a property isn't identified as enumerable, the loop will ignore that it's within the object.

如果一个属性未被标识为可枚举的,循环将忽略它在对象内。

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"


A property is identified as enumerable or not by its own [[Enumerable]]attribute. You can view this as part of the property's descriptor:

属性由其自身的[[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 }

A for..inloop then iterates through the object's property names.

for..in则遍历对象的属性名称进行迭代。

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

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

But, only evaluates its statement – console.log(prop);in this case – for those properties whose [[Enumerable]]attribute is true.

但是,仅console.log(prop);针对属性为 的那些属性评估其语句(在这种情况下[[Enumerable]]true

This condition is in place because objects have many more properties, especially from inheritance:

这个条件是存在的,因为对象有更多的属性,特别是继承

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

Each of these properties still exists on the object:

这些属性中的每一个仍然存在于对象上

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

But, they're skipped by the for..inloop because they aren't enumerable.

但是,它们被for..in循环跳过,因为它们不可枚举。

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

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

回答by carpeliam

If you create an object via myObj = {foo: 'bar'}or something thereabouts, all properties are enumerable. So the easier question to ask is, what's not enumerable? Certain objects have some non-enumerable properties, for example if you call Object.getOwnPropertyNames([])(which returns an array of all properties, enumerable or not, on []), it will return ['length'], which includes the non-enumerable property of an array, 'length'.

如果您通过myObj = {foo: 'bar'}或其他方式创建对象,则所有属性都是可枚举的。所以更容易问的问题是,什么是不可枚举的?某些对象具有一些不可枚举的属性,例如,如果您调用Object.getOwnPropertyNames([])(它返回一个包含所有属性的数组,无论是否可枚举,在 [] 上),它将返回['length'],其中包括数组的不可枚举属性 'length' .

You can make your own non-enumerable properties by calling Object.defineProperty:

您可以通过调用来创建自己的不可枚举属性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'

This example borrows heavily from Non-enumerable properties in JavaScript, but shows an object being enumerated over. Properties can either be or not be writable, configurable, or enumerable. John Resig discusses this in the scope of ECMAScript 5 Objects and Properties.

这个例子大量借鉴了 JavaScript 中的不可枚举属性,但显示了一个被枚举的对象。属性可以是或不可写的、可配置的或可枚举的。John Resig 在ECMAScript 5 对象和属性的范围内讨论了这一点。

And, there's a Stack Overflow question about why you'd ever want to make properties non-enumerable.

并且,有一个 Stack Overflow 问题,关于为什么您想要使属性不可枚举

回答by Gabriel Kunkel

It's a lot more boring than something that should be visualized.

它比应该可视化的东西要无聊得多。

There is literally an attribute on all properties called "enumerable." When it is set to false the for..inmethod will skip that property, pretend it doesn't exist.

从字面上看,所有属性上都有一个称为“可枚举”的属性。当它设置为 false 时,该for..in方法将跳过该属性,假装它不存在。

There are a lot of properties on objects that have "enumerable" set to false, like "valueOf" and "hasOwnProperty," because it's presumed you don't want the JavaScript engine iterating over those.

将“enumerable”设置为 false 的对象上有很多属性,例如“valueOf”和“hasOwnProperty”,因为假设您不希望 JavaScript 引擎迭代这些属性。

You can create your own non-enumerable properties using the Object.definePropertymethod:

您可以使用以下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..inor Object.keysit will remain completely secret:

但是,他们必须首先知道该财产是否存在,因为如果他们试图通过它访问它,for..in否则Object.keys它将完全保密:

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

They should have just called it, "forInAble."

他们应该直接称它为“forInAble”。

回答by Paul S.

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 nonenumerableproperty existsbut is partially hidden; meaning that nonenumerableis 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

我觉得有点像这样,一个不可枚举的属性存在但部分隐藏;这意味着不可枚举是奇怪的。现在您可以将 enumerable 想象为剩下的东西——自从我们发现Objects以来,我们习惯遇到的更自然的属性。考虑

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

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

现在在 a 中for..in,把它想象成伪代码

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 JavaScriptis in the place of /* whatever */

您在JavaScript中键入的循环主体所在的位置/* whatever */

回答by Ved

I will write one line definition of ENUMERABLE

我将编写ENUMERABLE 的一行定义

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

Enumerable:指定是否可以在 for/in 循环中返回该属性。

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

回答by Jeshawn Chrite

Think of the enum data type, just a structure of objects that correspond to different numbers. To declare something to as an enumerable is to declare that it corresponds to a specific number, allowing it to be given a place in a Dictionary that represents countable components of an object. To put it simply, making an object enumerable is the same as telling the compiler, "Hey, this property counts, I want to see this when I check for data on this object."

想想枚举数据类型,只是一种对应不同数字的对象结构。将某物声明为可枚举的就是声明它对应于一个特定的数字,从而允许它在表示对象的可数组件的 Dictionary 中占有一席之地。简单来说,让一个对象可枚举就等于告诉编译器,“嘿,这个属性很重要,我想在我检查这个对象上的数据时看到这个。”

回答by parveen mittal

Built-in methods that objects inherit are not enumerable, but the properties that your code adds to objects are enumerable unless explicitly stated

对象继承的内置方法不可枚举,但除非明确说明,否则您的代码添加到对象的属性是可枚举的

回答by user316264

methods are not enumerable; or rather built in methods are not.. tho after searching on what enumerablemeans 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"

方法不可枚举;或者更确切地说,内置方法不是......在搜索了可枚举对java脚本的含义之后;它只是指一个属性属性.. ecma3 中所有创建的对象都是可枚举的,而 ecma5 你现在可以定义它.. 就是这样.. :D lol 花了我一点时间找到答案;但我相信它在大卫弗拉纳根的书中谈到过......所以我猜它的意思是“隐藏”,或者不是“隐藏”,因为方法没有显示在 for in 循环中,因此是“隐藏的”