写一个函数offOne(word, book)
一个名为word
的字符串和一个名为book
的字符串数组。
它返回同一个word
中所有book
的数组
长度是一个字母不同。
示例:
offOne("cat", ["cat", "fat", "flat", "tar"]) => ["fat", "tar"]
offOne("will", ["wilt", "willow", "wail"]) => ["wilt", "wail"]
目前我的职能是:
function offOne(word, book) {
var array = [];
var count = 0;
for (var i = 0; i < book.length; i++) {
if (book.length === word.length) {
if (word.indexOf(book[i]) !== -1) {
count += 1;
if (count === (book[i].length - 1)) {
array.push(book[i]);
}
}
}
}
return array;
}
有谁知道如何解决这个问题?我在这里遇到了一段时间。
答案 0 :(得分:1)
这些摘要通过评论很好地解决了。它应该对你有所帮助。做检查!
准备工作的要点:
filter
而不是foreach
一样。这些会减少你的工作。Logical operators
。祝你好运!
我这样做
var word = "cat";
var book = ["car", "far", "mars", "call", "bat"]
function compare(elm, word) {
var i = 0
elm.split('').forEach(c => { //tokenize elm of book into array
if (word.indexOf(c) > -1) //check if charecter in present in the word
i += 1 //if yes, increment
})
return i === word.length - 1 ? true : false //return true if length of i is (length of word - 1),
}
function offOne(word, book) {
return book.filter(elm =>
// check, if the length of both strings are not same and
// both strings are not same and
// compare strings, true will be returned if the condition is satisfied in compare()
elm.length === word.length && elm !== word && compare(elm, word)
)
}
console.log(offOne(word, book))
&#13;
我的先进方式
如果你看到,这个函数中没有声明任何变量。
var word = "cat";
var book = ["car", "far", "mars", "call", "bat"]
function compare(elm, word) {
return elm.split('').filter(c => //tokenize elm of book into array
word.indexOf(c) > -1 //check if charecter in present in the word, if yes, return true
).join('').length === word.length - 1 ? true : false //join and check the length of the array is one less than length of the word, if yes, return true
}
function offOne(word, book) {
return book.filter(elm =>
// check, if the length of both strings are not same and
// both strings are not same and
// compare strings, true will be returned if the condition is satisfied in compare()
elm.length === word.length && elm !== word && compare(elm, word)
)
}
console.log(offOne(word, book))
&#13;
答案 1 :(得分:0)
将单词转换为字母数组,使此数组唯一。对于每个书籍数组项目都做同样的事情并计算它们之间不同字符的数量。如果只找到一个差异,则返回该项目,对每个项目重复。