[英]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.