JavaScript 支持集合吗?

发布于 2024-10-09 07:27:31 字数 160 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不醒的梦 2024-10-16 07:27:31

你的钥匙是字符串吗?

每个 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.

梦途 2024-10-16 07:27:31

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.

羞稚 2024-10-16 07:27:31

现在有了 ES6(以及像 corejs 这样的 polyfills/shims),你就拥有了它们:

设置 - JavaScript | MDN

示例:

var mySet = new Set([1, 2, 3, 2, 1]);  // => [1, 2, 3]
console.log(mySet.size);
console.log(mySet.has(3));
mySet.forEach(function(x){console.log(x)});

Polifill 是必需的,因为旧版浏览器不支持它,因此如果您只针对最新浏览器,可以忽略它。

Now with ES6 (and polyfills/shims like corejs) you have them:

Set - JavaScript | MDN

Example:

var mySet = new Set([1, 2, 3, 2, 1]);  // => [1, 2, 3]
console.log(mySet.size);
console.log(mySet.has(3));
mySet.forEach(function(x){console.log(x)});

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.

耳钉梦 2024-10-16 07:27:31

您可能还记得 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 - the for (var x in ...) is part of the "native" JS as far as I know and is supported by all browsers.

青芜 2024-10-16 07:27:31

JavaScript 支持 Set。以下是 canIuse 网站的链接。 Chrome、Edge、Safari、Firefox、Opera 甚至 IE 都支持它。要声明集合,您可以使用 Set() 构造函数。

let set = new Set();
set.add("John);

这样就可以使用集合了。

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.

let set = new Set();
set.add("John);

In this way you can use sets.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文