新增函数switch的测试

光庆 2月前 664

Code AardioLine:13复制
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
    • 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函数看起来有点抽象,其实就是从一个全是“函数类型”成员的表里面,取到合适的成员(函数),执行并返回执行结果。

    这个函数表,可以是数组(有序、稀疏)、也可以是字典(键值对)。但不变的是:值一定要是函数。

    为了便于理解,自己写个函数模拟一下这种逻辑:

    Code AardioLine:19复制
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
    • //简单定义
    • 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))

    或者可以进行更详细、准确的判断:

    Code AardioLine:20复制
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
    • //更详细准确的定义
    • 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))


    最新回复 (2)
    • sdf 2月前
      0 2
      比官方透彻!👍
    • demo 2月前
      0 3
      实际应用有栗子不,感觉不好用在什么地方
    返回