正文 3216字数 418,959阅读

如果不使用if语句的话,代码会更加接近代码即数据的概念。

示例1: 统计数组中的奇数
假设我们有一个整数数组arrayOfIntegers,现在需要统计其中奇数的个数:
const arrayOfIntegers = [1, 4, 5, 9, 0, -1, 5];
Run code
Cut to clipboard

    使用if
    let counter = 0; arrayOfIntegers.forEach((integer) => { const remainder = Math.abs(integer % 2); if (remainder === 1) { counter++; } });
    Run code
    Cut to clipboard

      console.log(counter);
      不用if
      let counter = 0; arrayOfIntegers.forEach((integer) => { const remainder = Math.abs(integer % 2); counter += remainder; }); console.log(counter);
      Run code
      Cut to clipboard

        不用if时,巧妙地利用了奇数与偶数的特性,它们除以2的余数分别是0和1。

        示例2: 判断工作日和周末
        给定一个日期(比如new Date()),判断它是工作日还是周末,分别返回”weekend”和”weekday”。

        使用if
        const weekendOrWeekday = (inputDate) => { const day = inputDate.getDay(); if (day === 0 || day === 6) { return 'weekend'; } return 'weekday'; // Or, for ternary fans: // return (day === 0 || day === 6) ? 'weekend' : 'weekday'; }; console.log(weekendOrWeekday(new Date()));
        Run code
        Cut to clipboard

          不用if
          const weekendOrWeekday = (inputDate) => { const day = inputDate.getDay(); return weekendOrWeekday.labels[day] || weekendOrWeekday.labels['default']; }; weekendOrWeekday.labels = { 0: 'weekend', 6: 'weekend', default: 'weekday' }; console.log(weekendOrWeekday(new Date()));
          Run code
          Cut to clipboard

            是否发现if语句中其实隐含着一些信息呢?它告诉我们哪一天是周末,哪一天是工作日。
            因此,要去掉if语句的话,只需要把这些信息写入
            weekendOrWeekday.labels
            Run code
            Cut to clipboard
              对象,然后直接使用它。

              示例3: doubler函数
              写一个doubler函数,它会根据参数的类型,进行不同的操作:

              如果参数是数字,则乘以2(i.e. 5 => 10, -10 => -20);
              如果参数是字符串,则每个字符重复2次 (i.e. 'hello' => 'hheelloo');
              如果参数是函数,则调用2次;
              如果参数是数组,则将每一个元素作为参数,调用doubler函数
              如果参数是对象,则将每个属性值作为参数,调用doubler函数

              使用switch
              const doubler = (input) => { switch (typeof input) { case 'number': return input + input; case 'string': return input .split('') .map((letter) => letter + letter) .join(''); case 'object': Object.keys(input) .map((key) => (input[key] = doubler(input[key]))); return input; case 'function': input(); input(); } }; console.log(doubler(-10)); console.log(doubler('hey')); console.log(doubler([5, 'hello'])); console.log(doubler({ a: 5, b: 'hello' })); console.log( doubler(function() { console.log('call-me'); }), );
              Run code
              Cut to clipboard

                不用switch
                const doubler = (input) => { return doubler.operationsByType[typeof input](input); }; doubler.operationsByType = { number: (input) => input + input, string: (input) => input .split('') .map((letter) => letter + letter) .join(''), function: (input) => { input(); input(); }, object: (input) => { Object.keys(input) .map((key) => (input[key] = doubler(input[key]))); return input; }, }; console.log(doubler(-10)); console.log(doubler('hey')); console.log(doubler([5, 'hello'])); console.log(doubler({ a: 5, b: 'hello' })); console.log( doubler(function() { console.log('call-me'); }), );
                Run code
                Cut to clipboard

                  将每一种参数类型对应的操作绑定到
                  doubler.operationsByType
                  Run code
                  Cut to clipboard
                    ,这样不需要switch语句,就可以实现doubler函数。


                    原文: Coding Tip: Try to Code Without If-statements