对于循环,如何在一行上显示每个字符

时间:2015-01-06 08:23:26

标签: javascript string for-loop

var text = prompt("What is Lance trying to say"); 
//user type any text

for (var i = 0; i <= text.length; i++)
{
    var result = text.charAt(i);

    if (result == "e" || result == "o" || result == "a" || result == "u")
    {
        result = "i";
    }
    else if (result != "e")
    {
        result == result;
    }
    console.log(result);

}

结果我现在有用户输入&#34;你好&#34;

h

i

l

l

i

如何在一行中获得每个单个字符。

4 个答案:

答案 0 :(得分:1)

您可以使用列表存储所需的字符并加入:

  var text = prompt("What is Lance trying to say"); 
  //user type any text
  var char_list = [];

  for (var i = 0; i <= text.length; i++) {

    var result = text.charAt(i);

    if (result == "e" || result == "o" || result == "a" || result == "u") {
      char_list.push("i");
    }else if (result != "e") {
      char_list.push(result);
    }
  }

  console.log(char_list.join(''));

答案 1 :(得分:1)

以下是一些不同的比较方法:

使用一系列if语句。请注意,for语句使用更紧凑的语法。

var text = prompt("What is Lance trying to say"); 
//user type any text

var result = "";
for (var i in text) {
    var ch = text.charAt(i);
    if (ch == "e" || ch == "o" || ch == "a" || ch == "u") {
        result = result + "i";        
    } else {
        result = result + ch;        
    }
}
console.log(result);

使用switch语句

var text = prompt("What is Lance trying to say"); 
//user type any text

var result = "";
for (var i in text) {
    var ch = text.charAt(i);
    switch (ch) {
        case "e": case "o": case "a": case "u":
            result = result + "i"
            break;
        default:
            result = result + ch;
            break;
    }
}
console.log(result)

使用正则表达式和三元运算符以及+ =运算符将值附加到字符串

var text = prompt("What is Lance trying to say"); 
//user type any text

var result = '';

for (var i in text) {
    result += function(ch) {
        return ch.match(/[eoau]/) ? "i" : ch
    }(text.charAt(i));
}
console.log(result);

祝你学习顺利。

答案 2 :(得分:0)

不是每次都返回字母,而是将结果附加到单个变量。循环完成后返回变量

答案 3 :(得分:0)

我想这就是你想要实现的目标 - 没有数组连接和推送操作作为请求。我还在for循环中修复了<=;并且else if没有意义,只有else是正确的

var text = prompt("What is Lance trying to say"); 
//user type any text

var collect = '';

for (var i = 0; i < text.length; i++) {
    var result = text.charAt(i);

    if (result == "e" || result == "o" || result == "a" || result == "u") {
        collect += "i";
    } else {
        collect += result;
    }
}

console.log(collect);