如何循环遍历JS集合并在找到值时中断?

问题描述 投票:0回答:2

我有 2 组 URL。我想循环遍历一组并将每个值与

.has
与第二组进行比较。

为此我有:

  urlSet1.forEach(function(value) {
    if (urlSet2.has(value) == false) {
      newUrl = value;
      return false;
    }
  })

但是,当然,这会继续循环。

我尝试使用

every
但出现错误:

urlSet1.every is not a function

当然

break;
也不适用于此。

有人知道如何实现这一目标吗?

javascript arrays set
2个回答
2
投票

您应该使用

for
循环。

for (const url of urlSet1) {
  if (!urlSet2.has(url)) {
    newUrl = url;
    break;
  }
}

1
投票

如果您的目标是继续运行循环直到满足条件,那么您可以将条件逻辑嵌套在

while loop
中,并使用
boolean
标志来停止循环运行。

现在,您也可以使用

break;
,因为正在使用 while 循环,但布尔标志也同样有效,无需重新安排逻辑。

请参阅下面片段中的注释:

var urlSet1 = new Map()
urlSet1.set('abc.com', 'def.com', 'ghi.net', 'jkl.com')

var urlSet2 = new Map()
urlSet2.set('abc.com', 'def.net', 'ghi.com', 'jkl.com')

var newUrl = ''

//set a boolean flag to use as condition for while loop
var running = true

//while running is true, continue running loop
while (running) {
  urlSet1.forEach(function(value) {
    if (urlSet2.has(value) == false) {
      newUrl = value;
      console.log(newUrl)
      //once condition is met, set boolean flag to false to stop loop
      running = false;
      console.log(running)
    } else {
      //some other condition
    }
  })
}

© www.soinside.com 2019 - 2024. All rights reserved.