带有字符串和整数的 Javascript 警报语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15072302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:23:51  来源:igfitidea点击:

Javascript alert statement with string & int

javascript

提问by user1050619

Im a newbie to Javascript and trying to debug a simple js function..I need to get the value of x through the alert statement but it doesn't display correctly..How to concatenate a string and int as in this case..

我是 Javascript 的新手,正在尝试调试一个简单的 js 函数。我需要通过警报语句获取 x 的值,但它无法正确显示。

<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>

New code:

新代码:

<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>

回答by Mike Thomsen

alert("Value of x" + x);

JavaScript is a dynamic language. The conversion is done automatically for you. When you do something like "var x = string + int"

JavaScript 是一种动态语言。转换会自动为您完成。当您执行诸如“var x = string + int”之类的操作时

Update

更新

The reason your alert is failing now is because you start the alert with a double quotation mark and end the string piece of the alert with a single quote.

您的警报现在失败的原因是您以双引号开始警报并以单引号结束警报的字符串部分。

回答by Lloyd

You can just do:

你可以这样做:

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

No need to call valueOfthe conversion will be automatic (implicit).

无需调用valueOf转换就会自动(隐式)。