$('#toggle-linecolor').click(function () {
chart.yAxis[0].update({
lineColor: lineColor
});
lineColor = { red: 'blue', blue: 'red' }[lineColor];
});发布于 2015-07-02 18:02:33
它在'red'和'blue'之间切换。
假设你是这样开始的:
var lineColor = 'red';执行此操作会将lineColor更改为“blue”
lineColor = { red: 'blue', blue: 'red' }[lineColor];
// The property [red] of that object has a value of 'blue'
lineColor // <--- 'blue'再次执行它,它会将值切换为“red”
lineColor = { red: 'blue', blue: 'red' }[lineColor];
// The property [blue] of that object has a value of 'red'
lineColor // <---- 'red'发布于 2015-07-02 18:02:11
它交换/切换颜色。红色-->蓝色,蓝色-->红色
lineColor = 'blue';
lineColor = { red: 'red', blue: 'blue' }[lineColor]; // 'red'等同于
lineColor = { red: 'red', blue: 'blue' }.blue; // 'red'发布于 2015-07-02 18:08:48
这是一种聪明的方法,可以将toggle实现为one liner。你可以像这样解压它:
var lineColor = 'red';
function toggleColor(){
chart.yAxis[0].update({
lineColor: lineColor
});
var opposites = { red : 'blue', blue : 'red' };
if( lineColor == 'red' ){
lineColor = opposites.red; // assigns 'blue' to lineColor
}
else if( lineColor == 'blue' ){
lineColor = opposites.blue; // assigns 'red' to lineColor
}
// but you can shorten the above if/else statement to:
lineColor = opposites[ lineColor ];
// which can be shortened to this if you don't want to
// assign the opposites object to a variable:
lineColor = { red: 'blue', blue: 'red' }[lineColor];
}注释后编辑:可以使用两种以上的颜色创建循环序列:
opposites = { red : 'green', green : 'yellow', yellow : 'blue', blue : 'red' };因此,如果当前颜色是红色,则更改为绿色,如果是绿色,则更改为黄色,如果是黄色,则更改为蓝色,如果是蓝色,则更改为红色:http://jsfiddle.net/p3bw04vw/
https://stackoverflow.com/questions/31181444
复制相似问题