How do I combine 2 javascript variables into a string

后端 未结 5 874
有刺的猬
有刺的猬 2020-12-03 03:40

I would like to join a js variable together with another to create another variable name... so it would be look like;

for (i=1;i<=2;i++){
    var marker =         


        
相关标签:
5条回答
  • 2020-12-03 03:53

    You can use the JavaScript String concat() Method,

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

    Its syntax is:

    string.concat(string1, string2, ..., stringX)
    
    0 讨论(0)
  • 2020-12-03 03:59

    warning! this does not work with links.

    var variable = 'variable', another = 'another';

    ['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');
    
    0 讨论(0)
  • 2020-12-03 04:04

    ES6 introduce template strings for concatenation. 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!
    
    0 讨论(0)
  • 2020-12-03 04:07

    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;
    
    0 讨论(0)
  • 2020-12-03 04:08

    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
    
    0 讨论(0)
提交回复
热议问题