以下JavaScript代码可以使用,但有一种更简洁的方法可以使用 n 参数将其写入" eval" y 1 轴,y 2 轴,y 3 轴字段名称?
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;
}
答案 0 :(得分:1)
编辑:误读了这个问题,抱歉!
您可以使用静态密钥而不是您需要更改的密钥,然后动态更改它,以便:
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
});
答案 1 :(得分:1)
尝试:
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}}]
.....];
然后可以更换开关(n):
collections[n]