
import console;
var list = {
abc=λ()"我是字典abc";
λ()"我是有序1";
[100]=λ()"我是稀疏100";
default:λ()"我是字典Default";
}
console.dump(switch("abc",list))
console.dump(switch(1,list))
console.dump(switch(100,list))
console.dump(switch(4,list))
console.dump(switch(,list))
console.pause();
switch函数看起来有点抽象,其实就是从一个全是“函数类型”成员的表里面,取到合适的成员(函数),执行并返回执行结果。
这个函数表,可以是数组(有序、稀疏)、也可以是字典(键值对)。但不变的是:值一定要是函数。
为了便于理解,自己写个函数模拟一下这种逻辑:
//简单定义
var SwitchByGodking = function(index,list,default,...){
var func = list[index] : default : list["default"];
if type(func)==="function" return func(...);
}
//执行测试
import console;
import console;
var list = {
abc=λ()"我是字典abc";
λ()"我是有序1";
[100]=λ()"我是稀疏100";
default:λ()"我是字典Default";
}
console.dump(SwitchByGodking("abc",list))
console.dump(SwitchByGodking(1,list))
console.dump(SwitchByGodking(100,list))
console.dump(SwitchByGodking(4,list))
console.dump(SwitchByGodking(,list))
或者可以进行更详细、准确的判断:
//更详细准确的定义
var SwitchByGodking = function(index,list,default,...){
if type(list)!=="table" error("参数2必须指定一个待检索的表对象");
if type(list[index])==="function" return list[index](...);
if type(default)==="function" return default(...);
if type(list["default"])==="function" return list["default"](...);
}
//执行测试
import console;
var list = {
abc=λ()"我是字典abc";
λ()"我是有序1";
[100]=λ()"我是稀疏100";
default:λ()"我是字典Default";
}
console.dump(SwitchByGodking("abc",list))
console.dump(SwitchByGodking(1,list))
console.dump(SwitchByGodking(100,list))
console.dump(SwitchByGodking(4,list))
console.dump(SwitchByGodking(,list))