我目前遇到这个问题,我似乎无法找到针对我的问题的答案。
Array1 = ["item1", "item2", "item3", "item4", "item5"]
Array2 = ["item2", "item5"]
我希望使用 array2 中的信息在 array1 中查找。
输出示例
Array1 has item2 and is at Array1[1]
如果有人可以帮助我,谢谢。
最佳答案
Array2.forEach((e) => {
const indexOfE = Array1.indexOf(e)
if (indexOfE > -1) {
console.log(`Array1 has ${e} and is at Array1[${indexOfE}]`)
}
})
您可以查看forEach
, indexOf
,和template literals帮助您理解这段代码。
编辑
回答评论中的问题,如果你想检查Array1中包含Array2元素作为子字符串的元素,那么你可以:
Array2.forEach((e) => {
Array1.forEach((f, i) => {
if (f.toLowerCase().includes(e)) {
console.log(`Array1 has ${e} and is at Array1[${i}]`)
}
})
})
检查String.prototype.includes
和 this answer有关在另一个字符串中查找子字符串的详细信息。
关于javascript - 使用另一个数组从一个数组中查找信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335294/