【问题标题】:How to concatenate variables in javascript?如何在javascript中连接变量?
【发布时间】:2014-09-12 19:22:24
【问题描述】:

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

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

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

    return output;
}

【问题讨论】:

标签: javascript


【解决方案1】:

+ 运算符将连接两个字符串,即。 “你好”+“世界”//>“你好世界”。使用+= 是分配和连接变量及其自身的捷径。

即。而不是:

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

你可以这样做:

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

针对您的问题:

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(){

【讨论】:

  • @torazaburo 是的,我想这只是算术时代的习惯。已更新。
  • agconti。感谢回复 我的错误是我在做 var output = " "; var output += " ";我在第二个变量之后放了一个 var。但你的例子奏效了。谢谢!
  • @eldan221 如果我回答了你的问题,你能接受我的回答吗?
【解决方案2】:

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

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

结果:我的名字是:yourname yourlastname

【讨论】:

  • 您不能在未定义的变量上使用+=。您的代码甚至无法编译。
  • 感谢我没有看到那个基本错误。编辑了我的答案。
【解决方案3】:

使用Concat 函数或使用加号运算符(+)。

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

【讨论】:

  • concat 函数已弃用/推荐反对。
猜你喜欢
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2021-12-19
  • 2012-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多