测试是否已使用“每个”来提取项目,无法按预期工作

时间:2018-06-22 02:58:11

标签: javascript

我正在获取新标记。我正在测试是否已根据其ID提取了它们:

// newMarkers = [{ id: 1 }, { id: 2}]
// state.fetchedMarkers = [{ id: 1 }]

newMarkers.forEach(marker => {
  if (state.fetchedMarkers.every(fetchedMarker => fetchedMarker.id === marker.id)) {
    console.log('newMarkers HAVE BEEN fetched')
  } else {
    console.log('newMrakers HAVEN'T BEEN fetched')
    state.fetchedMarkers.concat(newMarkers)
    // they haven't been fetched so I'm putting them in the fetched array
  }
})

但是不管我做什么,“已获取”始终运行,而“尚未获取”永远不会运行。

我的if语句可能有问题吗?也许every在这里不是正确的选择?

2 个答案:

答案 0 :(得分:1)

let newMarkers = [{ id: 1 }, { id: 2}]
let fetchedMarkers = [{ id: 1 }]

newMarkers.forEach(marker => {
  if (fetchedMarkers.every(fetchedMarker => fetchedMarker.id === marker.id)) {
    console.log('newMarkers HAVE BEEN fetched')
  } else {
    console.log('newMrakers HAVENT BEEN fetched')
    fetchedMarkers.concat(newMarkers)
    // they haven't been fetched so I'm putting them in the fetched array
  }
})

您共享的代码不完整,或者newMarkersfetchedMarkers的值不完整,ifelse都在使用您的代码运行提供了。只需点击Run code snippet

答案 1 :(得分:1)

使用fetchedMarkers.every将检查每个与ID匹配的对象。因此,如果fetchedMarkers数组的值大于1,则会给出错误的答案。将fetchedMarkers.every替换为fetchedMarkers.some可以很好地工作。

let newMarkers = [{ id: 1 }, { id: 2}]
let fetchedMarkers = [{ id: 1 }, { id: 3 }]

newMarkers.forEach(marker => {
  if (fetchedMarkers.some(fetchedMarker => fetchedMarker.id === marker.id)) {
    console.log('newMarkers HAVE BEEN fetched')
  } else {
    console.log('newMrakers HAVENT BEEN fetched')
    fetchedMarkers.concat(newMarkers)
    // they haven't been fetched so I'm putting them in the fetched array
  }
})