我可以使用参数来定义字段名称吗

Can I use parameter to define field name

下面的 JavaScript 代码可以工作,但是有没有更紧凑的方法可以使用 n 参数将其编写为 "eval" y1axis,y2axis,y3axis字段名?

  switch (n) {
    case 1:
      markingsY = [
             { color: colorErr, y1axis: { from: maxVal } },
             { color: colorErr, y1axis: { to: minVal } },
             { color: "#00f", lineWidth: 1, y1axis: { from: minVal, to: minVal } },
             { color: "#00f", lineWidth: 1, y1axis: { from: maxVal, to: maxVal } }
          ];
    break;

    case 2:
      markingsY = [
             { color: colorErr, y2axis: { from: maxVal } },
             { color: colorErr, y2axis: { to: minVal } },
             { color: "#00f", lineWidth: 1, y2axis: { from: minVal, to: minVal } },
             { color: "#00f", lineWidth: 1, y2axis: { from: maxVal, to: maxVal } }
          ];
    break;

    case 3:
      markingsY = [
             { color: colorErr, y3axis: { from: maxVal } },
             { color: colorErr, y3axis: { to: minVal } },
             { color: "#00f", lineWidth: 1, y3axis: { from: minVal, to: minVal } },
             { color: "#00f", lineWidth: 1, y3axis: { from: maxVal, to: maxVal } }
          ];
    break;

    default:
    break;


  }

编辑:看错问题了,抱歉!

您可以使用静态密钥代替您需要更改的密钥,然后动态更改它,因此:

markingsY = [
    { color: colorErr, yaxis: { from: maxVal } },
    { color: colorErr, yaxis: { to: minVal } },
    { color: "#00f", lineWidth: 1, yaxis: { from: minVal, to: minVal } },
    { color: "#00f", lineWidth: 1, yaxis: { from: maxVal, to: maxVal } }
];
markingsY.forEach(function(item){
    item["y"+n+"axis"]=item.yaxis;//copy it to its new key
    delete item.yaxis;//remove the old one
});

尝试:

var n = 10

    var collections = [];
    for(var i = 0; i < 10; i++){
        var json1 = {}
      var row = [];
      json1['color'] = '#000000';
      json1['y'+i+'axis'] = {from: 1234};
      row.push(json1);
      collections.push(row);
    }

    console.log(collections);

您将拥有 10 个 markingsY 数组的集合。 每个 markingsY 数组都有(我的代码)1 JSON

collections = [ 
    [{color:#0000000, y0axis:{form:1234}}], 
    [{color:#0000000, y1axis:{form:1234}}] 
.....];

那你的switch(n)就可以换成:

collections[n]

https://jsfiddle.net/kingychiu/ow1e3h4x/