我想要一个在字符串中查找单词的方法,它必须是整个数组,而不是字符串上的子数组(就像array.includes((所做的那样(
const key = ['one','two','three']
let message = 'onepiece'
key.forEach((j) => {
//string.prototype.includes()
if(message.includes(j)) console.log('Method1',true); //In this way is true always there is a 'one', no matter if the string is just 'one' or 'onepiece' or 'one piece'
else console.log('Method1',false)
//array.prototype.includes()
if(j.includes(message)) console.log('Method2',true); //In this way is true when message = 'one'
else console.log('Method2',false)
});
下面的代码完成了我想要的
const key = ['one','two','three']
let message = 'one'
for (var i=0 ; message[i]!=undefined ; i++){
mes = message.split(" ")[i]
if(key.includes(mes)) console.log(true) //In this way is true when the message contains 'one', no matter if it's alone or in a string, but false if it's 'onepiece'
}
我觉得这个代码效率很低,我的问题是有没有更简单的方法来实现这个函数?
Thx!
听起来像是在寻找两个数组之间的交集,因为您通过拆分messsage
来将其视为一个数组。在这种情况下,您可以使用array.some()
来检查key
中是否有单词存在于message
:中
const key = ['one', 'two', 'three']
let message = 'one'
let mes = message.split(' ')
let result = key.some(val => mes.includes(val))
console.log(result)
//Result is true for 'one'
//Result is true for 'one piece'
//Result is false for 'onepiece'