如何检查数组中是否存在字符串



我想遍历数组并检查数组元素中是否存在字符串,下面的代码部分有效。目前的问题是,如果指定字符串存在于数组元素的任何位置,它就会记录数组元素,但我想做的是,如果字符串在数组元素中,而且索引位置相同,它就会记录日志。为了更好地解释这一点,说我的数组元素之一是testing,我要寻找的字符串是tes,因为tes出现在索引位置0,1,2元素日志。但是说我的数组元素是not testing,我正在寻找的字符串是tes,它不会记录,因为即使字符串存在,它在错误的索引。我怎样才能做到这一点呢?提前谢谢。

const myArray = ['test blah', 'this is test', 'testing 234', 'nothing']
const check = 'te'
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].includes(check)) {
//should print myArray[0] and myarray[2]
console.log(myArray[i]);
}
}

您可以使用startsWith()

const myArray = ['test blah', 'this is test', 'testing 234', 'nothing']
const check = 'tes'
for (let i = 0; i < myArray.length; i++) {
if (myArray[i].startsWith(check)) {
console.log(myArray[i]);
}
}