Javascript索引

时间:2016-03-14 16:37:38

标签: javascript

基本上我有一个字符串(句子)和一个字符串数组(单词),我试图将我的字符串或句子与我的数组中的每个字符串进行比较。如果它在字符串或句子中找到数组中的任何字符串,它应返回true并对其执行某些操作。我正在寻找一种更快更好的方法来在javaScript中做这样的事情。下面是我编写的代码示例

function search() {
    var sentence = "you are a good and amazing friend, you are also fast"
    var words = ["crazy", "lovely", "good", "amazing", "beautiful", "ugly", "fast"];

    //validity 
    var yes = true;

    for (var i = 0; i < words.length; i++) {
        var word = words[i];

        if (sentence.indexOf(word) != -1) {
            yes = true;
            console.log(word + " found in " + sentence)
        } else {
            yes = false;
            console.log(word + " wasnt found in " + sentence)
        }
    }

    function validity() {
        if (yes == true) {
            alert(word + "thank you, you are a good friend")
        } else {
            alert(word + "thank you")
        }
    }

    validity();
}

search();

2 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.some()

plotOptions: {
            series: {
                dataLabels: {
                    enabled: true,
                    format: '{point.name}'
                }
            },
            bubble: {
              color: 'white',
              marker: {
                  fillColor: 'transparent'
              }
          }
        },

在ES6中,您可以使用箭头功能使此代码更短:

var sentence = 'you are a good and amazing friend, you are also fast';
var words = ["crazy", "lovely", "good", "amazing", "beautiful", "ugly", "fast"];

var isValid = words.some(function(w) {
    return sentence.indexOf(w) > -1;
});

console.log(isValid); // true

答案 1 :(得分:0)

var sentence = "you are a good and amazing friend, you are also fast";
var words = ["crazy", "lovely", "good", "amazing", "beautiful", "ugly", "fast"];

function check(item){
return sentence.search(item) > -1;
}

new_array = words.filter(check);

[“好”,“惊人”,“快”]

//do something with new_array that contains your matches