简体   繁体   English

如何将 2 个 javascript 变量组合成一个字符串

[英]How do I combine 2 javascript variables into a string

I would like to join a js variable together with another to create another variable name... so it would be look like;我想将一个 js 变量与另一个变量连接在一起以创建另一个变量名......所以它看起来像;

for (i=1;i<=2;i++){
    var marker = new google.maps.Marker({
position:"myLatlng"+i,
map: map, 
title:"title"+i,
icon: "image"+i
}); 
}

and later on I have后来我有

myLatlng1=xxxxx;
myLatlng2=xxxxx;

Use the concatenation operator + , and the fact that numeric types will convert automatically into strings:使用连接运算符+ ,以及数字类型将自动转换为字符串的事实:

var a = 1;
var b = "bob";
var c = b + a;

warning!警告! this does not work with links.这不适用于链接。

var variable = 'variable', another = 'another'; var 变量 = '变量', 另一个 = '另一个';

['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');

ES6 introduce template strings for concatenation. ES6 引入了用于连接的模板字符串。 Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings.模板字符串使用反引号 (``) 而不是我们习惯于使用常规字符串的单引号或双引号。 A template string could thus be written as follows:因此,模板字符串可以写成如下:

// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);

// => "Yo, Brendan!"

var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

//=> JavaScript first appeared 20 years ago. Crazy!

You can use the JavaScript String concat() Method,你可以使用 JavaScript String concat() 方法,

var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"

Its syntax is:它的语法是:

string.concat(string1, string2, ..., stringX)

if you want to concatenate the string representation of the values of two variables, use the + sign :如果要连接两个变量值的字符串表示形式,请使用+符号:

var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1

But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:但是,如果您想将两者仅保留在一个变量中,但仍可以在以后访问它们,则可以创建一个对象容器:

function Container(){
   this.variables = [];
}
Container.prototype.addVar = function(var){
   this.variables.push(var);
}
Container.prototype.toString = function(){
   var result = '';
   for(var i in this.variables)
       result += this.variables[i];
   return result;
}

var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1

the advantage is that you can get the string representation of the two variables, bit you can modify them later :优点是您可以获得两个变量的字符串表示形式,稍后您可以修改它们:

container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM