JavaScript 支持集合吗?
Javascript 是否支持集合(仅包含唯一对象的列表)?
我找到了 这个链接,但据我所知,并不是所有浏览器都支持 JS 中的 foreach 。
Does Javascript supports Sets(list with unique objects only) ?
I have found this link, but from what I remember foreach in JS in not supported by every browser.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的钥匙是字符串吗?
每个 JavaScript 对象都是一个映射,这意味着它可以表示一个集合。
如您提到的页面所示,每个对象仅接受每个键(属性名称)的一份副本。键/属性的值并不重要。
Are your keys strings?
Every JavaScript object is a map, which means that it can represent a set.
As illustrated in the page you mentioned, each object will accept only one copy of each key (attribute name). The value for the key/attribute doesn't matter.
jshashtable 允许您将任何对象存储为密钥,并使用与你给的链接。此外,它还提供了一种获取键数组的方法,然后您可以对其进行迭代。它还具有良好的跨浏览器支持,因此应该能够很好地适应任何环境。
jshashtable would allow you to store any object as a key, and use the same pattern as in the link you gave. In addition it supplies a method to get an array of keys, which you can then iterate over. It also has good cross-browser support, so should fit nicely into any environment.
现在有了 ES6(以及像 corejs 这样的 polyfills/shims),你就拥有了它们:
设置 - JavaScript | MDN
示例:
Polifill 是必需的,因为旧版浏览器不支持它,因此如果您只针对最新浏览器,可以忽略它。
Now with ES6 (and polyfills/shims like corejs) you have them:
Set - JavaScript | MDN
Example:
The Polifill is required since it is not supported by older browsers, so you can ignore it if you are aiming only at the latest ones.
您可能还记得
Array.forEach()
,它确实不受旧版 Opera 和所有 IE 浏览器的支持 -for (var x in ...)
是据我所知,“原生”JS 被所有浏览器支持。You probably remember the
Array.forEach()
that is indeed not supported by older Opera and all IE browsers - thefor (var x in ...)
is part of the "native" JS as far as I know and is supported by all browsers.JavaScript 支持 Set。以下是 canIuse 网站的链接。 Chrome、Edge、Safari、Firefox、Opera 甚至 IE 都支持它。要声明集合,您可以使用 Set() 构造函数。
这样就可以使用集合了。
JavaScript do support Set. Here is the link to canIuse website. It is supported by Chrome, Edge, Safari, Firefox, Opera and even IE. To declare set you can use Set() constructor.
In this way you can use sets.