javascript - 为什么集合的键等于值?

标签 javascript arrays set key

这本书

Understanding ECMAScript 6

声明

Sets don’t have keys, however. The people behind the ECMAScript 6 standard could have made the callback function in the set version of forEach() accept two arguments, but that would have made it different from the other two. Instead, they found a way to keep the callback function the same and accept three arguments: each value in a set is considered to be the key and the value. As such, the frst and second argument are always the same in forEach() on sets to keep this functionality consistent with the other forEach() methods on arrays and maps.

为什么不像数组那样创建键?
其背后的动机是什么?

最佳答案

从某种意义上说,Set s 实际上确实有索引,如果没有键的话..

从逻辑上讲,集合甚至没有定义的迭代顺序,更不用说键了。但事实是,new Set([1, 2, 3])的迭代与 new Set([3, 1, 2]) 的顺序不同.

这就是数学和编程之间的区别。

<小时/>

更新:问题已根据评论的讨论进行了更新

<小时/>

键/索引确实不应该存在。如果有一种合理的方法可以避免这种情况,我认为他们会这样做。但在编程中,我们不能只是说“对于集合 s 中的所有 S ...”,我们需要能够迭代那些 s 。的。但我们不应该寻找比这个迭代更多的东西。尽可能,new Set([1, 2, 3])new Set([3, 1, 2])行为应该尽可能相似。

想象一下,如果我们序列化一个 Trie 来存储集合 {'baby', 'bad', 'bank', 'box', 'dad', 'dance'}(b(a(b(y)dn(k))o(x))d(a(dn(c(e))))) 。那根本没有索引。提供这些的唯一原因是保留 forEach各种类型尽可能保持一致。套装不如其他套装合适。仅此而已。

换句话说,重用该值(或者一致地传递一些不相关的标记)比假装迭代索引是 Set 中有意义的部分更有意义。界面。排序是偶然的,实现细节是必要的,因为程序员无法使用数学技术。但它不是 Set 的基本接口(interface)的一部分s。

关于javascript - 为什么集合的键等于值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48690839/

相关文章:

javascript - jQuery HeapBox "this"事件内部

javascript - 将箭头键映射到滚轮功能?

Java-数组 : How do i find the number that has a similar digit most times?

C++迭代器到集合的最后一个元素

arrays - Swift Array 按属性交集

javascript - 通过ajax发布请求似乎无法正常工作

javascript - 单击其中的链接时隐藏 div

c++ - 尝试在类定义中声明数组时出错

c - 重置 char *array[size] 内容

c++ - 为什么设置迭代器指针会导致段错误?