5

Javascript の初心者で、単純な js 関数をデバッグしようとしています.alert ステートメントを使用して x の値を取得する必要がありますが、正しく表示されません..この場合のように文字列と int を連結する方法..

<html>
    <head>
    </head>
    <body>
        <script>
            function displaydate()  
            {
                document.getElementById("test").innerHTML='first line changed';
                document.getElementById("test1").innerHTML='second line changed';
                var x = 5;
                alert("Value of x" + String.valueOf(x));
            }
        </script>
        <p id="test">this is the 1st line</p>
        <p id="test1">this is the 2nd line</p>
        <button type="button" onclick="displaydate()">clickme!</button>

    <body>
</html>

新しいコード:

<html>
    <head>
    </head>
    <body>
        <script>
            function displaydate()  
            {
                document.getElementById("test").innerHTML='first line changed';
                document.getElementById("test1").innerHTML='second line changed';
                var x = 5;
                alert("Value of x=" + x);
                var cars=new Array();
                cars[0]='car';
                cars[1]='Volvo';
                alert("Value of arrary 1 var=' + cars[0]);
                //alert("Value of arrary 2 var='+cars[1]);
            }
        </script>
        <p id="test">this is the 1st line</p>
        <p id="test1">this is the 2nd line</p>
        <button type="button" onclick="displaydate()">clickme!</button>

    <body>
</html>
4

2 に答える 2

11
alert("Value of x" + x);

JavaScript は動的言語です。変換は自動的に行われます。「var x = string + int」のようなことをすると

アップデート

アラートが失敗する理由は、アラートを二重引用符で開始し、アラートの文字列部分を単一引用符で終了したためです。

于 2013-02-25T17:05:10.480 に答える
5

あなたはただ行うことができます:

alert("Value of x - " + x);

変換を呼び出す必要はありませんvalueOf(暗黙的)。

于 2013-02-25T17:04:14.127 に答える