My understanding of how the switch
statement works inside the CPU is not completely clear, but I have a theory. I believe that when the switch statement is entered, the value of the variable color
is temporarily stored for comparison. Subsequently, each assignment within the cases is evaluated against this stored switch-value, rather than directly comparing with the variable itself. To support my hypothesis, consider the following scenario:
var color = 'whit'
switch(color + 'e')
// "white" is stored for comparison...
{
case color = 'green':
case color = 'red':
case color = 'blue':
case color = 'pink':
alert('colorful')
break;
case color = 'black':
// (color = 'white') == 'white'
// The stored value is compared with 'white'
case color = 'white':
alert('classical')
break;
default:
alert('dull')
break;
}
UPDATE:
In the subsequent example, the value
is fetched only once, at the start of the switch statement, yet it is set multiple times within the case statements. This demonstrates that solely the value of the variable (rather than the variable itself) is utilized for comparison.
function Field(val){
this.__defineGetter__("value", function(){
var val = parseInt(Math.random() * 10);
console.log('get: ' + val);
return val;
});
this.__defineSetter__("value", function(val){
console.log('set: ' + val);
});
}
var field = new Field();
switch (field.value) {
case field.value = 0:
break
case field.value = 1:
break
case field.value = 2:
break
case field.value = 3:
break
case field.value = 4:
break
case field.value = 5:
break
case field.value = 6:
break
case field.value = 7:
break
case field.value = 8:
break
case field.value = 9:
break
default:
break
}
// output (e.g.)
// get: 5
// set: 1
// set: 2
// set: 3
// set: 4
// set: 5