javascript - Js 函数应该返回一个特定的字符串,但行为怪异
问题描述
我知道这应该是一项非常简单的任务,但我正在尝试更多地了解 JS 及其行为方式,这个函数的行为应该是这样的:
如果单词以辅音开头,则取第一个辅音或辅音簇,将其移动到单词的末尾,并在其上添加“ay”。
如果单词以元音开头,只需在末尾添加“way”即可。
例子:
加利福尼亚 => aliforniacay
算法 => algorithmway
schwartz => artzschway
california 和 algorithm 单词按预期工作,但 schwartz 没有,我的输出是:omarigg@omarigg-System:$ node pigLatinExercise.js
chwartzsay
hwartzscaywartzschay
artzschway
<= 我的预期结果
schwartzway
我不明白为什么变量 newPhrase2 在 else 范围内等于“artzschway”,但是当我在 for 范围之外返回相同的变量时,将其值更改为“schwartzway”
我该如何处理这个范围问题?我也知道用正则表达式工具解决这个问题更可行,但我想以这种方式处理这个问题,以了解更多信息。
function translatePigLatin(str) {
var arrayToAdd = [];
function cond(index) {
return (str[index] === 'a' ||
str[index] === 'e' ||
str[index] === 'i' ||
str[index] === 'o' ||
str[index] === 'u')
}
for (var i = 0; i <= str.length + 1; i++) {
if (cond(i)) {
//console.log('vowel at first')
var newPhrase2 = str + 'way'
break
//console.log(str)
} else {
//console.log('not vowel at first')
let theWord = str[i];
arrayToAdd.push(theWord);
//console.log(arrayToAdd)
let newPhrase = str.slice(i + 1, str.length + 1)
//console.log(newPhrase);
let newPhrase2 = newPhrase + arrayToAdd.join("") + 'ay'
console.log(newPhrase2);
}
}
//console.log(arrayToAdd.join(""));
// arrayToAdd.join("");
// newPhrase = newPhrase + arrayToAdd + 'ay'
//console.log(newPhrase2)
return newPhrase2;
}
console.log(translatePigLatin("schwartz"))
解决方案
请尝试此代码,它应该可以正常工作!
function translatePigLatin(str) {
let stringToAdd = '';
let newPhrase2 = '';
let newPhrase = '';
function cond(index) {
return (str[index] === 'a' ||
str[index] === 'e' ||
str[index] === 'i' ||
str[index] === 'o' ||
str[index] === 'u')
}
if (cond(0)) {
newPhrase2 = str + 'way';
console.log(newPhrase2);
return newPhrase2;
}
else {
for (let i = 0; i < str.length; i++) {
let theWord = str[i];
if(!cond(i)) {
stringToAdd += theWord;
newPhrase = str.slice(i + 1, str.length + 1);
}
else break;
}
}
newPhrase2 = newPhrase + stringToAdd + 'ay';
console.log(newPhrase2);
return newPhrase2;
}
translatePigLatin("schwrz");
您的代码无法正常工作的原因是您弄乱了条件逻辑。
您应该在不进入循环的情况下检查第一个字母。如果它不是元音,则进入循环并循环直到找到元音。
我认为在那之后它是不言自明的。
推荐阅读
- kubernetes - Kubernetes Pod 终止不会立即发生,必须等到宽限期到期
- xslt - XSLT/XPATH : 处理 XHTML 文件以将分隔的文本部分转换为新类
- python - 在 Python 中绘制方波
- typescript - 将元素添加到打字稿 Record<>
- python - 如何在matplotlib中将坐标轴刻度格式化为有效数字
- python - 抓取网站时出错 (http.client.BadStatusLine: )
- nginx - elasticbeanstalk 不会复制我的 nginx 配置
- python - 获得每组的第 20 到第 80 个百分位数 - Pyspark
- python - Python:将文本写入数据库并读取它
- vb6 - 如何计算 MSFLEXGRID 中的可见列数