在這作業了幾個小時后,我迷失了如何解決以下問題。請提供帶有解釋或建議的解決方案,以改進我的解決方案。
/* instructions
Given a word and an array of string skeletons, return an array of all of the skeletons that could be turned into the word by replacing the '-' with letters. If there are no possible matches return an empty string example: given the word 'hello' 'he---' would
be a match, 'h--l' or 'g-llo' would not be a match */
// example test case:
let word = 'hello';
let skeletons = ['h--l', 'he---', 'g-llo', 'm-llo', '--llo', 'h-l--'];
function findSkels(word, skeleton){
let goodSkels = [];
skeleton = skeletons.filter(w => w.length === word.length);
console.log(skeletons)
for(let sw = 0; sw < skeletons.length; sw ){
let possibleMatch = true;
for(let letter = 0; letter < word.length; letter ){
if(word[letter] !== skeletons[sw][letter] || skeletons[sw][letter] == '-'){
possibleMatch = false
}
}
if(possibleMatch){
goodSkels.push(skeletons[sw])
}
}
return goodSkels;
}
uj5u.com熱心網友回復:
你很近,但是
if (word[letter] !== skeletons[sw][letter] || skeletons[sw][letter] == '-') {
possibleMatch = false
}
如果任何字母不匹配或字母是-. 因此,這將取消任何不完全匹配的單詞的資格。相反,您想要&&- 僅當字母不匹配且字母不是-.
/* instructions
Given a word and an array of string skeletons, return an array of all of the skeletons that could be turned into the word by replacing the '-' with letters. If there are no possible matches return an empty string example: given the word 'hello' 'he---' would
be a match, 'h--l' or 'g-llo' would not be a match */
// example test case:
let word = 'hello';
let skeletons = ['h--l', 'he---', 'g-llo', 'm-llo', '--llo', 'h-l--'];
function findSkels(word, skeleton) {
let goodSkels = [];
skeleton = skeletons.filter(w => w.length === word.length);
for (let sw = 0; sw < skeletons.length; sw ) {
let possibleMatch = true;
for (let letter = 0; letter < word.length; letter ) {
if (word[letter] !== skeletons[sw][letter] && skeletons[sw][letter] !== '-') {
possibleMatch = false
}
}
if (possibleMatch) {
goodSkels.push(skeletons[sw])
}
}
return goodSkels;
}
console.log(findSkels(word, skeletons));
或者,重構為更好看:
const word = 'hello';
const skeletons = ['h--l', 'he---', 'g-llo', 'm-llo', '--llo', 'h-l--'];
const findSkels = (word, skeletons) => skeletons
.filter(skel => (
skel.length === word.length &&
[...skel].every((char, i) => char === '-' || char === word[i])
));
console.log(findSkels(word, skeletons));
陣列方法通常是使代碼比基于索引的命令式for回圈更簡潔的好方法。如果您實際上并不關心索引,只關心被迭代的值,您通常可以for (let i =完全放棄構造,并使用陣列方法或 for..of。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441580.html
標籤:javascript 数组 嵌套的 比较
下一篇:查詢合并和匯入范圍
