javascript 如何在javascript中连接变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25815382/
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-28 05:04:11  来源:igfitidea点击:

How to concatenate variables in javascript?

javascript

提问by eldan221

I am trying to concatenate variables in inside a function and then return. In php we just put a period before the "=" but it is not working in javascript.

我试图在函数内部连接变量然后返回。在 php 中,我们只是在“=”之前放了一个句点,但它在 javascript 中不起作用。

Can someone please help me figure this one out?

有人可以帮我解决这个问题吗?

function NewMenuItem(){
    var output = "<input type='checkbox'> ";
    var output .= "<input type='text'> ";

    return output;
}

回答by agconti

The +operator will concatenate two strings, ie. "Hello" + " World" //> "Hello World". Using +=is a short cut for assigning and concatenating a variable with its self.

+运营商将连接两个字符串,即。"Hello" + " World" //> "Hello World"。Using+=是分配变量并将其与其自身连接的捷径。

ie. instead of:

IE。代替:

var myVar = "somestring";
myVar = myVar + "another String";

you can just do:

你可以这样做:

var myVar = "somestring";
myVar += "another String";

For your problem:

对于您的问题:

function NewMenuItem() {
    //This is just a small example. The end result is more broader then this
    var output = "<input type='checkbox'> ";
    output += "<input type='text'> ";
    return output;
} //end of NewMenuItem(){

回答by Santiago Nicolas Roca

"+=" is the standard way to concatenate in javascript;

"+=" 是 javascript 中的标准连接方式;

var a = "yourname";
var b = "yourlastname";
var name = a + b;
var complete_name = "my name is: ";
complete_name += name;

result : my name is: yourname yourlastname

结果:我的名字是:你的名字你的姓氏

回答by Academia

With Concatfunction or with plus operator (+).

Concat函数或带加号运算符(+)

Check this link jsfiddleto see a working example.

检查此链接jsfiddle以查看工作示例。