JavaScript初学者:字符串麻烦

时间:2012-03-02 01:20:53

标签: javascript

在我的代码顶部,我需要询问用户是否希望玩游戏。使用字符串函数查看答案的第一个字母并将其设为小写。如果他们的回答==“y”则玩游戏。我需要帮助取正确的第一个字母,并将其缩小。

<HTML>
<HEAD>
</HEAD>
<BODY>

<FORM NAME="testform">
<BR>
<BR>
<BR>
</FORM>

<INPUT id="attempts" TYPE="text" NAME="inputbox" VALUE="" />
<INPUT id="zero" TYPE="button" NAME="resetbox" VALUE="Reset " onclick="reset()" />

<SCRIPT type="text/javascript">

varattempts = 0
x = Math.round((Math.random()*19))+1    
var tip

tip=prompt("Do you want to play a game?")

while(tip == "y")

{

    var Guess;
    document.getElementById('attempts').value = 0;
    do {

    Guess = prompt("Pick a number between 1 and 20","")
    if (Guess === null) break;
    document.getElementById('attempts').value = parseInt(document.getElementById('attempts').value)+1
      } while (Guess!=x);

    if (Guess == x)

    {

    alert("You guessed right!")

    }
}

function reset()

{
    varattempts=0;
    document.getElementById('attempts').value = 'Attempts: 0'; 
}

</SCRIPT>
</BODY>
</HTML>

1 个答案:

答案 0 :(得分:2)

要获取任何字符串的第一个字母,您可以使用.charAt(0)

var firstChar = myString.charAt(0);

并将其转换为小写:

var firstChar = myString.charAt(0).toLowerCase();

瞧!