简体   繁体   中英

Loop through array and evaluate expression

I am new to JS. I have the following syntax which I need to loop through array.

  {
    text: newcol[4],
    action: function (e, dt, node, config) {
      dt.order([[4, "desc"]]).draw();
    }
  }

Let's say I have an array var nOrder = [4,5]; I want the following syntax to be generated - above syntax is getting repeated twice (as per length of array) and taking values 4 and 5.

buttons = [
  {
    text: newcol[4],
    action: function (e, dt, node, config) {
      dt.order([[4, "desc"]]).draw();
    }
  },
  {
    text: newcol[5],
    action: function (e, dt, node, config) {
      dt.order([[5, "desc"]]).draw();
    }
  }
];

Is this what you need? I don't think you need to use JQuery.

function generateSyntax(array) { // The argument should be an array such as [4, 5]
    var resultSyntax = ""; // Every time you loop through the array, add some syntax here.

    resultSyntax += "buttons = [\n";
    for (var i in array) {
        resultSyntax += `  {
    text: newcol[` + array[i] + `],
    action: function (e, dt, node, config) {
      dt.order([[` + array[i] + `, "desc"]]).draw();
    }
  },\n`; // Add the syntax, with the number in between brackets ("[" and "]")
    }
    resultSyntax += "];"
    return resultSyntax;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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