为什么我的函数在使用另一个函数作为参数时返回未定义?

问题描述 投票:0回答:1

如果这个问题缺乏逻辑,我深表歉意。我遇到的问题是以下代码:

/**
 * @param {(sentence: string) => boolean} criterion - a function that
 *  takes a sentence and returns a boolean
 * @param {string[]} sentences - an array of space-separated strings of words
 * @returns {string[]} the subset of `sentences` for which `criterion` returns true
 */
const getRelevantSentences = (about, sentences) => {
    const arr = [];
      if(about(sentences) == true){
        arr.push(sentences);
        return arr;
      }
}

上面的函数应该接受另一个函数和一个数组作为参数,然后传递一个字符串数组,使函数返回 true。在本例中,我试图测试“sentence”数组中的特定“sentence”字符串是否使

about()
函数返回 true。换句话说,我返回与另一个字符串“相似”的任何字符串。

下面是构成

about()
函数的代码。

/**
 * @param {string[]} topics - an array of topic words
 * @param {string} sentence - a space-separated string of words
 * @returns {boolean} whether `sentence` contains any of the words in `topics`
 */
const isRelevant = (topics, sentence) => {
  for(i=0; i<topics.length;i++){
    if (sentence.includes(topics[i])) {
      return true;
    }
    else {
      return false;
    }
  }
};

/**
 * @param {string[]} topics - an array of topic words
 * @returns {(sentence: string) => boolean} a function that takes a sentence
 *  and returns whether it is relevant to `topics`
 */
const about = (topics) => {
    return function(sentence) {
      return isRelevant(topics,sentence);
    }
};

出于意图和目的,用作输入的数据是:

const sentence = "the quick brown fox jumps over the lazy dog"

const sentences = "I have a pet dog", "I have a pet cat", "I don't have any pets"

如果您需要更多数据,请告诉我。任何帮助是极大的赞赏!谢谢你。

javascript arrays string function currying
1个回答
0
投票

就目前情况而言,只要

undefined
about(sentences)
,该函数就不会返回任何内容 (
false
)。请重写该函数如下:

const getRelevantSentences = (about, sentences) => {
    const arr = [];
    if(about(sentences)){
        arr.push(sentences);
    }
    return arr;
}

或者,如下:

const getRelevantSentences = (about, sentences) => {
    if(about(sentences)){
        return [sentences];
    } else {
        return [];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.