JS: Interpolate a variable into a variable

时间:2018-03-25 20:42:43

标签: javascript interpolation

In the code below, I am trying to set the text for my 4 buttons. Would appreciate a helping hand with:

allButtons[i].innerHTML = btn${i}; 

and particularly with

btn${i}

I am trying to pass to .innerHTML the text stored above, but so far failed to do it. Most attempts I tried led to:

Uncaught SyntaxError: Unexpected token {

Question: how can I interpolate a variable into a variable in JS? The code:

  var btn0 = "Load tasks from server";
  var btn1 = "Load tasks from Local Storage";
  var btn2 = "Create tasks";
  var btn3 = "Edit tasks";

  var allButtons = document.getElementsByTagName('button');

  function setText( btn0, btn1, btn2, btn3, allButtons ) {
    var allButtons = document.getElementsByTagName('button');

    for (i = 0; i < allButtons.length; i++) {
      console.log(i);
      allButtons[i].innerHTML = btn${i}; // interpolation issue
    }
  }

3 个答案:

答案 0 :(得分:1)

You can't access a variable that way. The easiest solution is:

var btnTexts = ["Load tasks from server", "Load tasks from Local Storage", "Create tasks", "Edit tasks"];

var allButtons = document.getElementsByTagName('button');

function setText( allButtons ) {
    for (i = 0; i < allButtons.length; i++) {
        console.log(i);
        allButtons[i].innerHTML = btnTexts[i];
    }
}

// Then call the function using: setText(allButtons);

答案 1 :(得分:1)

You can't do that in js.

  • An alternative is using an object with the set of texts, and use the string interpolation (Template literals) to build the specific key + i.
  • Use textContent instead because is only text.

var btns = {
  btn0: "Load tasks from server",
  btn1: "Load tasks from Local Storage",
  btn2: "Create tasks",
  btn3: "Edit tasks"
}

function setText(allButtons) {
  for (i = 0; i < allButtons.length; i++) {
    allButtons[i].textContent = btns[`btn${i}`];
  }
}

var allButtons = document.getElementsByTagName('button');
setText(allButtons);
<button></button>
<button></button>
<button></button>
<button></button>

答案 2 :(得分:0)

ES6 interpolation works inside back-tick quotes strings, but it doesn't work in expressions like that.

The only thing that would work sort of the way you want -- and it's certainly not recommended -- would be to do an eval on an interpolated string. As someone else said, you're better off with an array.

NOT RECOMMENDED:

allButtons[i].innerHTML = eval(`btn${i}`);