字符串中变量的值不变

时间:2018-08-13 20:25:22

标签: javascript

我正在尝试创建一个函数,该函数使用字符串作为脚本模板来生成脚本。在这些模板字符串中,我有一个变量,它用作数组项的索引,如下所示:

var annotList = [ { type: "something", color: "blue" }]; // "annotation" objects are pushed in it

function generateScript() {
  var output = document.getElementById("output");

  var idx = 0; // array item index variable

  // template inserted in final template
  var addAnnot_template = 'this.addAnnot({ ' +
    'type:' + annotList[idx].type + ',' +
    'strokeColor: color.' + annotList[idx].color + ','

  // loop through an array named annotList, and increment the index for each items in order to add indexed template for each
  for (var i = 0; i < annotList.length - 1; i++) {
    idx++;
    addAnnot_template += addAnnot_template;
  }

  output.innerHTML = 'beginning of template' +

    addAnnot_template +

    'end of template';
}

我的问题是,即使在for循环中idx变量的值增加了,它也没有改变。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

您的问题是addAnnot_template变量已经设置,除非再次设置,否则不会更改。

将代码更改为此:

function generateScript() {
  var output = document.getElementById("output");

  var idx = 0; // array item index variable

  // loop through an array named annotList, and increment the index for each items in order to add indexed template for each
  for (var i = 0; i < annotList.length - 1; i++) {
    idx++;
    addAnnot_template += 'this.addAnnot({ ' +
        'type:' + annotList[idx].type + ',' +
        'strokeColor: color.' + annotList[idx].color + ',';
  }
  // code....
}

此外,您可以只使用i而不是idx,因为两者都从0开始并在每个循环中加1。然后,您可以删除所有对idx

的引用

IE:

function generateScript() {
  var output = document.getElementById("output");

  // loop through an array named annotList, and increment the index for each items in order to add indexed template for each
  for (var i = 0; i < annotList.length - 1; i++) {
    addAnnot_template += 'this.addAnnot({ ' +
        'type:' + annotList[i].type + ',' +
        'strokeColor: color.' + annotList[i].color + ',';
  }
  // code....
}