我是JavaScript新手。目前,我正在制作一个程序,我希望将文本翻译成" rovarspracket"。即每个辅音都加倍并且出现" o"之间。对于例如:翻译("这很有趣")应该返回字符串" tothohisos isos fofunon" 。我无法按照需要得到结果。帮助我,我会学习。
这是我试过的以下代码。
<button type="button" onclick="translate('de')">try it</button>
<h2 id="ad" />
<script>
function translate(t)
{//alert(t.length);exit;
var l=t.length;
var v=["a","e","i","o","u",""];
var b="";
for(var i=0;i<l;i++)
{ //alert(i);exit;
var c=t.charAt[i];alert(c);
if(v.indexOf(c)!=-1)
{
b=(b+(c));
}
else
{
b=(b+(c="o"+c));
}
}
document.getElementById("ad").innerHTML=b;
}
</script>
答案 0 :(得分:1)
我已经冒昧地为您简化了功能:
var str = "this is fun",
arr = str.split(''); // Split the string into an array of separate characters.
mapped = arr.map(function(c){
if(["a","e","i","o","u"," "].indexOf(c) == -1) // If the character is a consonant
return c + 'o' + c; // replace it,
return c; // otherwise, just keep the current character.
}),
result = mapped.join(''); // Rebuild the string
console.log(result);
&#13;
或者,更紧凑:
var str = "this is fun",
result = str.split('').map(function(c){
return (["a","e","i","o","u"," "].indexOf(c) == -1) ? (c + 'o' + c) : c;
}).join('');
console.log(result);
&#13;
答案 1 :(得分:0)
这是你可以做的事情。
function translate(input) {
var outputString = [];
var vowels = ['a', 'e', 'i', 'o', 'u'];
input.split("").forEach(function(charValue) {
if (vowels.includes(charValue) || charValue == ' ') {
outputString.push(charValue);
} else {
outputString.push(charValue + 'o' + charValue);
}
});
document.querySelector("#output").innerHTML = outputString.join("");
}
&#13;
div {
padding: 10px;
}
&#13;
<button type="button" onclick="window.translate('this is fun')">try it</button>
<div id="output"></div>
&#13;
如果您正在寻找具有charAt功能的解决方案,请点击此处。
function translate(input) {
var outputString = [],
vowels = ['a', 'e', 'i', 'o', 'u'];
for (var idx = 0; idx < input.length; idx++) {
var currentChar = input.charAt(idx);
if (vowels.indexOf(currentChar) === -1 && currentChar != " ") {
outputString.push(currentChar + "o" + currentChar);
} else {
outputString.push(currentChar);
}
}
console.log(outputString.join(""));
}
translate("this is fun");
&#13;