我有下面的数组,我想在输入“ca”时获取所有三个值的位置,这样它会返回 1,2,3
const withoutAccent = ["xyz", "can", "cant", "cannot"]
let test = withoutAccent.indexOf(withoutAccent.includes("ca"));
console.log(test)
最佳答案
你可以使用reduce
- 遍历数组
- 检查str是否存在于当前元素中
- 如果存在,则将当前索引添加到最终输出,否则不添加
let arr = ["xyz", "can", "cant", "cannot"]
let test = (str) => {
return arr.reduce((op, inp, i) => {
if (inp.includes(str)) {
op.push(i)
}
return op
}, [])
}
console.log(test('ca'))
旁注:-如果您想实现不区分大小写
inp.toLowerCase().includes(str.toLowerCase())
关于javascript - 如何从数组中获取所有单词的位置取决于包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57739867/