You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将函数作为参数传入时,我的JavaScript函数为何返回undefined?

函数返回undefined问题的修复方案

问题根源

  1. getRelevantSentences逻辑错误:
    • 未遍历sentences数组,反而把整个数组传给了about函数(about仅接受单个字符串)
    • 仅当传入的整个数组满足条件时才返回结果,否则函数无返回值,直接输出undefined
  2. isRelevant逻辑错误:
    • 循环中只要第一个topic不匹配就直接返回false,不会检查后续的topic词,导致漏判
  3. 输入数据格式错误:
    • sentences定义缺少数组括号,合法写法应包裹在[]内

修正后的完整代码

1. 修复isRelevant函数

/**
 * @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(let i=0; i<topics.length;i++){
    if (sentence.includes(topics[i])) {
      return true;
    }
  }
  return false; // 遍历完所有topic都不匹配时才返回false
};

2. 修复getRelevantSentences函数

/**
 * @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 = (criterion, sentences) => {
    const arr = [];
    // 遍历数组内的每一个句子
    for(const sentence of sentences) {
        if(criterion(sentence)) {
            arr.push(sentence);
        }
    }
    return arr; // 无论是否匹配到,都返回数组(空数组或匹配结果)
};

// 更简洁的写法可直接用数组filter方法:
// const getRelevantSentences = (criterion, sentences) => sentences.filter(criterion);

3. 正确的输入与调用示例

// 创建指定主题的判断函数
const dogTopics = ["dog"];
const aboutDogs = about(dogTopics);

// 正确定义句子数组
const sentences = ["I have a pet dog", "I have a pet cat", "I don't have any pets"];

// 调用函数并输出结果
const result = getRelevantSentences(aboutDogs, sentences);
console.log(result); // 输出: ["I have a pet dog"]

内容的提问来源于stack exchange,提问作者antjuh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:23:13