if(tab.name == 'first'){ myChart.setOption({ legend: { selected:{ [this.playNumber]:true, [this.coverNumber]:false, [this.touchNumber]:false, [this.winPrizeNum]:false, [this.takePrizeNum]:false } }, }) }else if(tab.name == 'second'){ myChart.setOption({ legend: { selected:{ [this.playNumber]:false, [this.coverNumber]:true, [this.touchNumber]:false, [this.winPrizeNum]:false, [this.takePrizeNum]:false } }, }) }else if(tab.name == 'third'){ myChart.setOption({ legend: { selected:{ [this.playNumber]:false, [this.coverNumber]:false, [this.touchNumber]:true, [this.winPrizeNum]:false, [this.takePrizeNum]:false } }, }) }else if(tab.name == 'fourth'){ myChart.setOption({ legend: { selected:{ [this.playNumber]:false, [this.coverNumber]:false, [this.touchNumber]:false, [this.winPrizeNum]:true, [this.takePrizeNum]:false } } }) }else if(tab.name == 'five'){ myChart.setOption({ legend: { selected:{ [this.playNumber]:false, [this.coverNumber]:false, [this.touchNumber]:false, [this.winPrizeNum]:false, [this.takePrizeNum]:true } } }) }
代码优化:
var arr = {'first':[this.playNumber],'second':[this.coverNumber],'third':[this.touchNumber],'fourth':[this.winPrizeNum],'five':[this.takePrizeNum]}; var obj = { [this.playNumber]:false, [this.coverNumber]:false, [this.touchNumber]:false, [this.winPrizeNum]:false, [this.takePrizeNum]:false }; Object.keys(arr).forEach(function(key){ if(tab.name == key){ obj[arr[key]] = true; } }); myChart.setOption({ legend: { selected: obj }, });