简洁的语法,如何写这个函数

a的结果可能是left、right、center
要求输出,left、right、center的对应的结果,分别对应top middle bottom

求一个简短的写法

阅读 1.7k
4 个回答

两个可以用条件运算符 (? :),三个也可以,@八尾狐 的回答。
但是三个以上最好就查表,@牛肉苏打 的回答。

除了映射表,也可以查数组表

const transform = (() => {
    const table = [
        ["left", "right", "center"],
        ["top", "bottom", "middle"], // 与原题顺序不一致,不知道是不是题主笔误
    ];

    return s => table[1][table[0].indexOf(s)];
})();

或者

const transform = (() => {
    const table = ["left", "right", "center", "top", "bottom", "middle"];
    return s => table[table.indexOf(s) + table.length / 2 | 0];
})();

当然一般来说都没有查映射表快

const position = {
  left: "top",
  right: "middle",
  center: "bottom"
};
const a = "left";
console.log(position[a]); // top

你的问题描述的不太清楚

 fn = (a: string) => {
        return a === 'left' ? 'top' : a === 'right' ? 'bottom' :  'center'
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题