将单词与数组中的单词进行比较

时间:2016-10-23 16:22:21

标签: javascript arrays

写一个函数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;
}

有谁知道如何解决这个问题?我在这里遇到了一段时间。

2 个答案:

答案 0 :(得分:1)

这些摘要通过评论很好地解决了。它应该对你有所帮助。做检查!

准备工作的要点:

  1. 不要声明不必要的变量。它消耗内存,这很糟糕。
  2. 不要使用不必要的循环。在使用循环之前检查可用的语言API。就像我使用filter而不是foreach一样。这些会减少你的工作。
  3. 始终考虑Logical operators
  4. 让代码变得简单。
  5. 祝你好运!

    我这样做

    &#13;
    &#13;
    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;
    &#13;
    &#13;

    我的先进方式

    如果你看到,这个函数中没有声明任何变量。

    &#13;
    &#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;
    &#13;
    &#13;

答案 1 :(得分:0)

将单词转换为字母数组,使此数组唯一。对于每个书籍数组项目都做同样的事情并计算它们之间不同字符的数量。如果只找到一个差异,则返回该项目,对每个项目重复。