【发布时间】:2022-10-04 20:29:49
【问题描述】:
下面两个 for 循环之间的唯一区别是 item1、item2、val1、val2、tooltip1、tooltip2。以及系列名称“Apple”、“Carrot”。此外,颜色“黑色”、“绿色”。 我有直到第8项。所以总共有 8 个 for 循环。谁能建议我如何减少下面代码中的行数。我相信这将有助于提高性能。谢谢你。
// plotlines
const item1 = [2, 6, 18]
const item2 = [5, 9, 30]
// ... have until item8
// For loop for item1
for( let val1 = 0; val1 < item1.length; val1++ ) {
if( id === 0 ) {
if( checked ) {
xAxis[0].addPlotLine( {
Tooltip1: true,
type: 'line',
value: item1[val1],
id: 'item1_' + item1[val1],
color: 'black',
width: 2,
zIndex: 2,
events: {
click: function( e ) {
var series = this.axis.series[0],
chart = series.chart,
PointClass = series.pointClass,
tooltip = chart.tooltip,
point = ( new PointClass() ).init(
series, ['Apple', this.options.value]
),
normalizedEvent = chart.pointer.normalize( e ),
tooltipEnabled = chart.lastClickedPoint ? chart.lastClickedPoint.id !== this.id : true;
chart.update( {
tooltip: {
enabled: tooltipEnabled
}
} );
point.tooltipPos = [
normalizedEvent.chartX - chart.plotLeft,
normalizedEvent.chartY - chart.plotTop
];
point.Tooltip1 = this.options.Tooltip1;
if( tooltipEnabled ) {
chart.lastClickedPoint = this;
} else {
chart.lastClickedPoint = null;
}
tooltip.refresh( point );
},
mouseout: function( e ) {
return false;
}
}
} );
} else {
xAxis[0].removePlotLine( 'item1_' + item1[val1] );
}
}
} // for loop ends
// For loop for item2
for( let val2 = 0; val2 < item2.length; val2++ ) {
if( id === 1 ) {
if( checked ) {
xAxis[0].addPlotLine( {
Tooltip2: true,
type: 'line',
value: item2[val2],
id: 'item2_' + item2[val2],
color: 'green',
width: 2,
zIndex: 2,
events: {
click: function( e ) {
var series = this.axis.series[0],
chart = series.chart,
PointClass = series.pointClass,
tooltip = chart.tooltip,
point = ( new PointClass() ).init(
series, ['Carrot', this.options.value]
),
normalizedEvent = chart.pointer.normalize( e ),
tooltipEnabled = chart.lastClickedPoint ? chart.lastClickedPoint.id !== this.id : true;
chart.update( {
tooltip: {
enabled: tooltipEnabled
}
} );
point.tooltipPos = [
normalizedEvent.chartX - chart.plotLeft,
normalizedEvent.chartY - chart.plotTop
];
point.Tooltip2 = this.options.Tooltip2;
if( tooltipEnabled ) {
chart.lastClickedPoint = this;
} else {
chart.lastClickedPoint = null;
}
tooltip.refresh( point );
},
mouseout: function( e ) {
return false;
}
}
} );
} else {
xAxis[0].removePlotLine( 'item2_' + item2[val2] );
}
}
}
【问题讨论】: