在查看 JavaScript 的新变化时,我注意到 Set
和 Map
使用 .size
而不是像数组那样的 .length
。
这似乎是对数组正常情况的毫无意义的转移 - 只需要记住一件事。
这有什么好的设计理由吗?
最佳答案
esdiscuss 线程中有很多讨论 "Set length property" .这是一个激烈争论的问题,因此您不一定同意该决议也就不足为奇了。
esdiscuss 中对此有大量争论。最终,盛行的论点(ES2015 的集合具有 size
而不是 length
的事实证明)在 a post by David Bruant 中进行了总结。 :
...for me 'length' refers to a measurement with something like a ruler. You start at 0 and see up to where it goes. This is very accurate for an array which is an indexed set (starting at 0 and growing) and for arrays as considered in C (continuous sequence of bytes) which ECMAScript arrays seem inspired of. This is probably less relevant for unordered collections such as sets which I'd tend to consider as a messy bag.
并在 a post by Dean Landolt 中进一步讨论:
Just wanted to jump in and say non-writable
length
is consistent with String behavior as well, but David makes a good point aboutlength
implying metric topology. David's suggestion ofcount
is nice. ISTM what we're talking about iscardinality
, but no need to get too silly w/ precision. Thoughsize
is just fine with me, and has plenty of prior art.
关于javascript - 为什么 JavaScript Sets/Maps 使用 `size` 而不是 `length` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35038750/