且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么..在获取所有的属性,但对于..没有得到所有的值?

更新时间:2023-11-21 08:18:40

for(... in ...)语法可用于任何对象,并将遍历该对象的所有属性。从技术上讲,这个循环将遍历对象内部由 [[Enumerbale]] 属性设置为true的属性。

The for (... in ...) syntax is available for use on any object, and will iterate over all properties of that object. More technically, this loop will iterate over any property in the object that's internally defined with its [[Enumerbale]] property set to true.

(... of ...)的 语法是ES6的新特性, strong>集合,而不是所有对象。它提供了迭代集合元素的简写方式,而不必使用或而$ c>循环与索引。它将以这种方式迭代任何具有 [Symbol.iterator] 属性的集合的任何元素。

The for (... of ...) syntax is new with ES6, and is specific to collections, rather than all objects. It provides a shorthand way to iterate over the elements of a collection, rather than having to use a plain for or while loop with an index. It will iterate in this manner over any the elements of any collection that has a [Symbol.iterator] property.

这不是一个不一致,它们是两个不同的运算符,用于两个不同的目的。我可以理解如何看起来像像 arr [boo] =moo将添加一个元素到数组 - 因为你可以访问数组的元素通过类似的语法,如 arr [0] 。但是很容易确认那些不一样 - 使用 arr [boo] =moo您正在创建一个也可以访问的属性通过 arr.boo ,但尝试访问数组的元素,例如, arr.0 将是一个语法错误,因为它们与属性不同。

This isn't an "inconsistency", they're two different operators intended to be used for two different purposes. I can understand how it might seem like doing something like arr["boo"] ="moo" would add an element to the array -- since you can access the array's elements via a similar syntax, as in arr[0]. But it's easy to confirm that those aren't the same in effect - with arr["boo"] ="moo" you're creating a property that can also be accessed by arr.boo, but attempting to access the elements of an array by, say, arr.0 would be a syntax error, because they aren't the same as properties.