let wordarray=[“defeat”,”dead”,”eaten”,”defend”,”ante”];
word =“defantmsi”;
posarray=“entfdenis”;
我是JavaScript的新手,并且在某个地方停留了一段代码。实际上,我想同时比较'word'和'posarray'并在'posarray'中找到丢失的字符,即'm'和'a',然后我必须在'wordarray'中找到字符串及其位置, t包含那些字符(m和a)。那么如何仅使用JavaScript来做到这一点呢?
预期的输出将是不包含字符m的a字符串和一个保卫的字符串。
答案 0 :(得分:0)
首先,我们通过与word
进行比较,从posarray
中获取丢失的字符。比起我们使用wordarray
和every
来检查includes
条件来过滤and
let wordarray=['defeat','dead','eaten','defend','ante', 'xyzam'];
let word ='defantmsi';
let posarray='entfdenis';
let missing = word.split('').filter(e=> !posarray.includes(e))
let op = wordarray.filter(e=> !missing.every(el=>e.includes(el)))
console.log(op)
答案 1 :(得分:0)
下面是您的示例代码
let wordarray=["defeat","dead","eaten","defend","ante","something"];
word ="defantmsi";
posarray="entfdenis";
function findMissingCharacters(str1,str2){
let result = [] //array which will be returned
for(let letter of str1){
//check if str2 doesnot contain letter of str1
if(!str2.includes(letter)) result.push(letter);
}
return result;
}
let missing = findMissingCharacters(word,posarray);
//filtering the wordarray
let strings = wordarray.filter(word =>{
//this boolean will be returned
let contains = false;
missing.forEach(letter => {
//check if any of letter in missing is in word
if(word.includes(letter)) contains = true;
})
//we don't want strings for which contains is true
return !contains;
})
console.log(strings);