JavaScript:压缩if else语句

时间:2018-12-05 02:52:05

标签: javascript if-statement

是否有更短的更有效的方法?似乎有点沉重,我只想知道它是否可以压缩?

'session' => [
        'save' => 'redis',
        'redis' => [
            'host' => 'redis',
            'port' => '6379',
            'password' => '',
            'timeout' => '2.5',
            'persistent_identifier' => '',
            'database' => '0',
            'compression_threshold' => '2048',
            'compression_library' => 'gzip',
            'log_level' => '1',
            'max_concurrency' => '10',
            'break_after_frontend' => '5',
            'break_after_adminhtml' => '30',
            'first_lifetime' => '600',
            'bot_first_lifetime' => '60',
            'bot_lifetime' => '7200',
            'disable_locking' => '1',
            'min_lifetime' => '60',
            'max_lifetime' => '2592000'
        ]
    ],
    'cache' => [
        'frontend' => [
            'default' => [
                'backend' => 'Cm_Cache_Backend_Redis',
                'backend_options' => [
                    'server' => 'redis',
                    'database' => '1',
                    'port' => '6379'
                ]
            ]
        ]
    ],

2 个答案:

答案 0 :(得分:6)

一种选择是使用字符数组,然后使用.indexOf查找字符的索引:

const word = 'bBac';
const chars = ['a', 'b', 'c', 'd'];

const y = [...word].map(char => chars.indexOf(char.toLowerCase()))
console.log(y);
// return y;

要获得更高的效率,请使用.indexOfO(N))代替Map(即O(1)):

const word = 'bBac';
const charMap = new Map([
  ['a', 0],
  ['b', 1],
  ['c', 2],
  ['d', 3]
]);

const y = [...word].map(char => charMap.get(char.toLowerCase()))
console.log(y);
// return y;

答案 1 :(得分:0)

您可以使用ASCII值,从而无需维护包含所有字母的结构:

let letterValue = word[i].toUpperCase().charCodeAt(0) - 65;  // 65 represents the offset of the alphabet in the ASCII table
if (letterValue >= 0 && letterValue <= 25) {  // Check that the value is A-Z
  y.push(letterValue);
}