简体   繁体   中英

Can someone explain to me how a function can equal 0?

function containsPunctuation(word)  
{
    var punctuation = [";", "!", ".", "?", ",", "-"];

    for(var i = 0; i < punctuation.length; i++)
    {
        if(word.indexOf(punctuation[i]) !== -1)
        {
          return true;
        }
    }

    return false;
}


function isStopWord(word, stopWords) 
{
    for (var i = 0; i < stopWords.length; i += 1) 
    {
        var stopWord = stopWords[i];

        if ((containsPunctuation(word)) && (word.indexOf(stopWord) === 0) && (word.length === stopWord.length + 1)) 
        {
            return true;
        } 
        else if (word === stopWord) 
        {
            return true;
        }
    }

    return false;
}

At the blockquote, how is containsPunctuation(word) && (word.indexOf(stopWord) === 0 ? Can someone explain why they are both equal to zero?

I'm also not sure why (word.length === stopWord.length + 1) is used.

I think you are reading the if statement a little bit incorrectly. Not knowing what the isStopWord function is supposed to do I can't tell you what the (word.length === stopWord.length + 1) part is all about.

I can tell you that (containsPunctuation(word)) is its own boolean value, because that function returns a true or false . That part is its own evaluation.

The second part (word.indexOf(stopWord) === 0) is also a complete evaluation. That part has nothing to do with the containsPunctuation function. The indexOf function returns an integer, so it can equal 0.

The third part (word.length === stopWord.length + 1) is checking to see if the length of word is one more than the length of stopWord .

They are all separate evaluations and because you are using && between them all, they all must evaluate as true in order for the code block that follows it to run.

Here are the indexOf docs for string and array:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

--EDIT-- in light of your comment, my guess for the (word.length === stopWord.length + 1) is because the word might contain a punctuation mark that is not included in the stopWord so this if check will only return true if the punctuation is at the end of the word because the indexOf check will only return 0 if the stopword starts at the beginning of the word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM