JavaScript Set 全新方法
2024-06-26 14:34 阅读(303)

Mozilla 开发者博客宣布,JavaScript Set 迎来了一系列新方法,这些方法已经在大多数主流浏览器引擎(从 Firefox 127 开始)中得到支持。这意味着开发者无需使用 polyfill 就能在各种浏览器上使用这些新方法。

新方法包括:

JavaScript Set 简介

Set 类似于数组,但每个值只能存储一次,确保了集合中元素的唯一性。与数组相比,检查元素是否存在于 Set 中通常更快,这在需要关注大型数据集性能的用例中非常适用。 此外,开发者还可以根据现有集合创建具有特定逻辑属性的新集合。

const dogs = new Set();
const yoshi = { name: "Yoshi", personality: "Friendly" };
dogs.add(yoshi);

新方法应用示例

// Create a union of both sets
const unionSet = set1.union(set2);

// List the items in the union
unionSet.forEach((item) => {
  const li = document.createElement("li");
  li.textContent = item;
  unionList.appendChild(li);
});


// Make the intersection set
const intersectionSet = set1.intersection(set2);

// Loop through lists and highlight if they're in the intersection
allListItems.forEach((item) => {
  if (intersectionSet.has(item.textContent)) {
    item.className = "match";
  }
});

const setNotBoth = set1.symmetricDifference(set2);

allListItems.forEach((item) => {
  if (setNotBoth.has(item.textContent)) {
    item.className = "match";
  }
});


const set1only = set1.difference(set2);
const set2only = set2.difference(set1);

allListItems.forEach((item) => {
  if (set1only.has(item.textContent)) {
    item.className = "setOneMatch";
  } else if (set2only.has(item.textContent)) {
    item.className = "setTwoMatch";
  }
});

isSubsetOf()、isSupersetOf() 和 isDisjointFrom() 方法: 用于检查集合之间的包含关系和不相交关系。

if (set1.isSubsetOf(set2)) {
  oneSubTwo.textContent += " [TRUE]";
} else {
  oneSubTwo.textContent += " [FALSE]";
}

详情查看:https://developer.mozilla.org/en-US/blog/javascript-set-methods/

返回顶部