我正在使用.some()和.includes()检查字符串是否包含数组中的一个或多个条目,如下所示。
如果该字符串确实包含数组中的一个或多个条目,我想知道是哪一个。到目前为止,我还没有找到实现此目标的方法。
这是我的代码:
var hobby = ["sport","art","music"];
var message = "I love sport!";
if(hobby.some(el => message.includes(el))){
console.log("a hobby is included");
// tell me which hobby or hobbies here
}
答案 0 :(得分:2)
使用.filter
代替.some
:
var hobby = ["sport", "art", "music"];
const checkMessage = (message) => {
const hobbies = hobby.filter(word => message.includes(word));
if (hobbies.length !== 0) {
console.log('Looks like you like ' + hobbies.join(','));
} else {
console.log('No matching hobbies found');
}
};
checkMessage("I love sport!");
checkMessage("foo bar");
checkMessage("music and art");
如果您想要匹配的索引,请使用.reduce
:
var hobby = ["sport", "art", "music"];
const checkMessage = (message) => {
const hobbyIndicies = hobby.reduce((a, word, i) => {
if (message.includes(word)) {
a.push(i);
}
return a;
}, []);
if (hobbyIndicies.length !== 0) {
console.log('Looks like you like indicies ' + hobbyIndicies.join(','));
} else {
console.log('No matching hobbies found');
}
};
checkMessage("I love sport!");
checkMessage("foo bar");
checkMessage("music and art");
答案 1 :(得分:2)
可以使用.filter()
方法代替.some()
来获取message
字符串中包含的项目列表。这又可以用来显示消息中的爱好。
该逻辑将涉及其他检查,以确保在将结果记录到控制台之前,已过滤列表的长度不为空:
var hobby = ["sport", "art", "music"];
var message = "I love sport!";
// Use .filter instead of .some
var result = hobby.filter(el => message.includes(el));
// If result not empty, log the result to console
if (result.length > 0) {
console.log("a hobby or hobbies are included:", result);
// To find matching indicies
const matchingIndicies = hobby
.map((str, index) => ({ str, index }))
.filter((item) => message.includes(item.str))
.map((item) => (item.str + ' at index ' + item.index));
console.log("matching indicies:", matchingIndicies)
// tell me which hobby or hobbies here
}
答案 2 :(得分:0)
我更喜欢一个简单的forEach
循环,如下所示:
var hobby = ["sport", "art", "music"];
var message = "I love sport!";
var idxs = []
var vals =[]
hobby.forEach(function(val, idx){
if (message.includes(val))
{
idxs.push(idx);
vals.push(val)
}
});
if (vals.length !== 0) {
console.log('You like ' + vals.join(','));
console.log('Your hobby indices: ' + idxs.join(','));
} else {
console.log('You Like Nothing!!');
}