繁体   English   中英

如何在 forEach 循环和 if 语句中正确返回字符串?

[英]How to properly return string in forEach loop and if statement?

我一直在做一个项目,但我一直在返回一个字符串。

现在让我向您展示代码:

export const returnAsString = (
  test: Array<TestQuestionAndAnswer>
) => {
  test.forEach((response) => {
    const fetchQuestion = getQuestionBasedOnId(response.questionId)
    fetchQuestion?.question.responses.forEach((res) => {
      if (
        res.responseId == response.responseId &&
        fetchQuestion.question.id == response.questionId
      ) {
        return `
        Question: ${fetchQuestion.question.text},
        Response: ${res.text}
        `
      }
    })
  })
}

现在这个 function 下一步应该做:输入的test是一个包含键值对对象的数组: questionId: id, responseId: id 我通过将 questionId 发送到一个 function 并返回它的文本,然后将其与测试数组中的 id 进行比较来找到两者的文本。 现在我需要以这种形式返回整个测试:

question: text, response: text
//new line
question: text, response: text
//new line
etc..

我不知道该怎么做。 我得到了值,但我无法得到一整串。 当我console.log这个 function 它返回未定义,但如果我console.log任何这些文本,它正在工作,但它被覆盖:

question 1,
response 1
//each line new output, overwriting old one
question 2,
response 2
question 3,
response 3
etc..

所以我的问题是如何返回一个完整的字符串? 我期待这样的事情:

question: question1, response: response1
question: question2, response: response2
question: question3, response: response3
...

但不是字符串相互覆盖,只有一个字符串。 有多个问题/回答。

编辑:

这就是我返回值的方式,但问题是首先返回未定义的值,然后返回undefined value1 value2..

export const returnAsString = (
  test: Array<TestQuestionAndAnswer>
) => {
  let string: any
  test.forEach((response) => {
    const fetchQuestion = getQuestionBasedOnId(response.questionId)
    fetchQuestion?.question.responses.forEach((res) => {
      if (
        res.responseId == response.responseId &&
        fetchQuestion.question.id == response.questionId
      ) {
        string = string + `
        Question: ${fetchQuestion.question.text},
        Response: ${res.text}
        `
      }
    })
  })
  return string
}

使用 arrays 工作得很好,但我需要返回一个字符串。

export const returnAsString = (
  test: Array<TestQuestionAndAnswer>
) => {
  let arr = new Array();
  test.forEach((response) => {
    const fetchQuestion = getQuestionBasedOnId(response.questionId)
    fetchQuestion?.question.responses.forEach((res) => {
      if (
        res.responseId == response.responseId &&
        fetchQuestion.question.id == response.questionId
      ) {
        arr.push({
        Question: fetchQuestion.question.text,
        Response: res.text
        })
      }
    })
  })
  return arr
}

Array#forEach不返回任何内容,您应该在此处使用其他 function。

export const returnAsString = (test: Array<TestQuestionAndAnswer>) => {
  return test
    .flatMap((response) => {
      const fetchQuestion = getQuestionBasedOnId(response.questionId);

      return fetchQuestion?.question.responses
        .filter(
          (res) =>
            res.responseId == response.responseId &&
            fetchQuestion.question.id == response.questionId
        )
        .map(
          (res) => `
        Question: ${fetchQuestion.question.text},
        Response: ${res.text}
        `
        );
    })
    .join("\n");
};

另外,假设fetchQuestion?.question.responses中只有一个res满足这个条件: res.responseId == response.responseId && fetchQuestion.question.id == response.questionId ,可以简化为:

export const returnAsString = (test: Array<TestQuestionAndAnswer>) => {
  return test
    .map((response) => {
      const fetchQuestion = getQuestionBasedOnId(response.questionId);

      const matchingResponse = fetchQuestion?.question.responses.find(
        (res) =>
          res.responseId == response.responseId &&
          fetchQuestion.question.id == response.questionId
      );

      if (matchingResponse) {
        return `
        Question: ${fetchQuestion.question.text},
        Response: ${matchingResponse.text}
        `;
      }

      return "":
    })
    .join("\n");
};

forEach不是用于返回值。 相反,您想要的是reduce ,它采用初始 object ,然后调用 function ,它获取上一个调用的返回值和下一个项目作为参数。

export const returnAsString = (test: Array<TestQuestionAndAnswer>) =>
    test.reduce((prev, response) => {
        const fetchQuestion = getQuestionBasedOnId(response.questionId);
        return (
            prev +
            fetchQuestion?.question.responses.reduce((prev, res) => {
                if (
                    res.responseId === response.responseId &&
                    fetchQuestion.question.id === response.questionId
                ) {
                    return `Question: ${fetchQuestion.question.text}, Response: ${res.text}\n`;
                }
                return '';
            }, '')
        );
    }, '');

这将提供预期的结果,但由于我们正在处理字符串,您可以使用join将其简化一点。

export const returnAsString = (test: Array<TestQuestionAndAnswer>) =>
    test
        // Flat map the arrays of response strings to one array
        .flatMap(response => {
            const fetchQuestion = getQuestionBasedOnId(response.questionId);
            return (
                // Map responses to stirngs
                fetchQuestion?.question.responses.map(res =>
                    // Switched to ternary here
                    res.responseId === response.responseId &&
                    fetchQuestion.question.id === response.questionId
                        ? // Return one string if condition is met
                          `Question: ${fetchQuestion.question.text}, Response: ${res.text}`
                        : // Return empty string if not since we must always return something
                          '',
                ) ?? []
            );
        })
        // Filter out empty rows
        .filter(r => r)
        // Join with new lines
        .join('\n');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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