如何使用javascript搜索单词中的字母?

时间:2015-06-17 15:48:52

标签: javascript arrays

假设我有字母a,b,s,d(比如)
我在数组中有100个单词。 我想使用js搜索包含所有字母的单词,并且只有满足所有字母,然后返回该单词。
我该怎么做?

1 个答案:

答案 0 :(得分:1)

好的,所以这是最初由user4703663发布的代码的扩展版本。我想等到他们有机会取消删除他们的答案,但他们从未这样做过。

var words = ['absd', 'dfsd', 'dsfefe', 'dfdddr', 'dfsgbbgah', 'dfggr'];

var str = 'absd';

function find(words, str) {

    // split the string into an array
    str = str.split('');

    // `filter` returns an array of array elements according
    // to the specification in the callback when a new word
    // is passed to it
    return words.filter(function (word) {

        // that callback says to take every element
        // in the `str` array and see if it appears anywhere
        // in the word. If it does, it's a match, and
        // `filter` adds that word to the output array
        return str.every(function (char) {
          return word.indexOf(char) > -1;
        });
    });
}

find(words, str); // [ "absd", "dfsgbbgah" ]

DEMO