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
How to concatenate variables in 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
结果:我的名字是:你的名字你的姓氏