我正在获取新标记。我正在测试是否已根据其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
在这里不是正确的选择?
答案 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
}
})
您共享的代码不完整,或者newMarkers
和fetchedMarkers
的值不完整,if
和else
都在使用您的代码运行提供了。只需点击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
}
})