【发布时间】:2019-08-23 18:09:43
【问题描述】:
猪拉丁作业。能够通过console.log获得正确的返回打印,但如果在node.js测试中运行脚本返回未定义。
在继续之前需要调试。
尝试将最终的函数调用移到脚本的其他位置。我想可能是因为范围,但这只是我的第二个 JS 项目,所以我真的是一个新手。
function pigLatin(word) {
// Global variables
const vowels = ["a", "e", "i", "o", "u"];
const splitWord = word
.toLowerCase()
.trim()
.split("");
// Slice Word at first Vowel to end
function firstPart(param1, param2) {
for (let v = 0; v < vowels.length; v++) {
for (let w = 0; w < splitWord.length; w++) {
if (vowels[w] === splitWord[v]) {
return `${splitWord.slice(v, splitWord.length).join("")}`;
} else if (splitWord.length === 1) {
return `${""}`;
}
}
}
}
// Slice word from First Letter to Vowel & if first letter is vowel
function secondPart(param1, param2) {
for (let v = 0; v < vowels.length; v++) {
for (let w = 0; w < splitWord.length; w++) {
if (vowels[w] === splitWord[0]) {
return `${splitWord.splice([0], [v]).join("")}yay`;
} else if (vowels[w] === splitWord[v]) {
return `${splitWord.splice([0], [v]).join("")}ay`;
} else if (splitWord.length === 1) {
return `${splitWord.join("")}yay`;
}
}
}
}
// Combine returns from firstPart and secondPart
const result1 = firstPart(vowels, splitWord);
const result2 = secondPart(vowels, splitWord);
function combine(param1, param2) {
return `${param1}${param2}`;
}
console.log(combine(result1, result2));
}
预期结果是脚本成功运行。但是当在 console.log 之外调用 combine(result1, result2) 时,脚本返回 undefined。
【问题讨论】:
-
什么返回未定义?你能用你如何调用你的方法来展示它吗?
-
对我来说很好jsfiddle.net/fdb9807s
-
用
return combine(result1, result2);替换console.log(combine(result1, result2));?这个问题有点不清楚,因为“脚本返回未定义”没有意义——脚本不能返回任何东西;只有函数可以返回值。也不确定“node.js 测试”是什么。 -
MultiplyByZer0:解决了这个问题。 node.js 测试是学校使用 mocha 设置的测试环境,以确保我们得到正确的结果。
标签: javascript node.js typescript