Search code examples
javascripthtmlconcatenation

Concatenation doesn't seem to work in JavaScript


I am doing something like this in my application. I have sequence of Id values like ID1, ID2 etc. I am trying to fetch the ID value using for loop.

Concatenation doesn't seem to work.

function Save(count,Id1,Id2,Id3){
  var response = [];
  for(var i=1;i <= count; i++) {
    value = `${'Id' + i}`;
    alert(value);
  }
}
<input type="button" value="Submit" onclick="Save(3,1,2,3)" />


Solution

  • You're creating a String "Id1", you cannot interpolate a variable name. But with ES6, you can use the rest parameters (...) to convert parts of your arguments to an Array:

    function Save(count, ...ids) {
      var response = [];
      for (var i = 0; i < count; i++) {
        value = ids[i];
        alert(value);
      }
    }
    <input type="button" value="Submit" onclick="Save(3,1,2,3)" />

    Before ES6, you would have to use arguments (that would convert all arguments):

    function Save() {
      var response = [];
      for (var i = 1; i <= arguments[0]; i++) {
        value = arguments[i];
        alert(value);
      }
    }
    <input type="button" value="Submit" onclick="Save(3,1,2,3)" />

    Or use eval, but don't. This is just for the example:

    function Save(count, Id1, Id2, Id3, Id4) {
      var response = [];
      for (var i = 1; i <= count; i++) {
        value = eval(`Id${i}`);
        alert(value);
      }
    }
    <input type="button" value="Submit" onclick="Save(3,1,2,3)" />