6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】ifやswitchを使いたくなくて変数名も考えたくない時の方法

Last updated at Posted at 2019-07-11

分岐が多くても見た目がカオスにならない三項演算子の代替的な何か。
ふと思いついたのでメモっておきます、結構便利。

ズバリ

JavaScript
const str = "aaa";
const num = 0;
const arg = "0123";

// 戻り値がある場合
const result = {
    "aaa": v => `${v}hoge`,
    "bbb": v => `${v}huga`
}[str](arg);

// 戻り値がない場合
({
    "aaa": v => console.log(`${v}hoge`),
    "bbb": v => console.log(`${v}huga`)
})[str](arg);

// プロパティ名ではなくメソッド名としてもOK
const result = {
    "aaa"(v){
        return `${v}hoge`;
    },
    "bbb"(v){
        return `${v}huga`;
    },
}[str](arg);

// オブジェクトの中身がリテラルや変数でもOK
const result = {
    "aaa": "hoge",
    "bbb": "huga"
}[str];

// 配列にも応用可能
const result = [
    v => `${v}00`,
    v => `${v}01`
][num](arg);

SpecialThanks!

6
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?