写好JavaScript条件语句的5条守则

照抄https://juejin.im/post/5bdef288e51d450d810a89c6
testEquals(fruit) {
if (fruit === 'apple' || fruit === 'strawberry') { console.log('=='); } }, testIncludes(fruit) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); } }, testMoreIf(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 条件 1: fruit 必须有值 if (fruit) { // 条件 2: 必须是red的 if (redFruits.includes(fruit)) { console.log('red'); // 条件 3: quantity大于10 if (quantity > 10) { console.log('big quantity'); } } } else { console.log('error'); } }, testMoreNoElse(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (!fruit) console.log('error'); if (!redFruits.includes(fruit)) return; console.log('red'); if (quantity > 10) console.log('big quantity'); }, testOrValue(fruit, quantity) { if (!fruit) return; // 如果 quantity 参数没有传入,设置默认值为 1 const q = quantity || 1; console.log(`We have ${q} ${fruit}!`); }, testDefaultValue(fruit, quantity = 1) { // 如果 quantity 参数没有传入,设置默认值为 1 if (!fruit) return; console.log(`We have ${quantity} ${fruit}!`); }, testSwitch(color) { // 使用条件语句来寻找对应颜色的水果 switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; } }, testInsteadOfSwitch(color) { const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] }; return fruitColor[color] || []; },
 //1.
      this.testEquals('apple'); //==
      this.testIncludes('apple'); //redz
      //2.
      this.testMoreIf(null); // error: No fruits
      this.testMoreIf('apple'); // print: red
      this.testMoreIf('apple', 20); // print: red, big quantity
      this.testMoreNoElse(null); // error: No fruits
      this.testMoreNoElse('apple'); // print: red
      this.testMoreNoElse('apple', 20); // print: red, big quantity
      //3.
      this.testOrValue('banana'); // We have 1 banana!
      this.testOrValue('apple', 2); // We have 2 apple!
      this.testDefaultValue('banana'); // We have 1 banana!
      this.testDefaultValue('apple', 2); // We have 2 apple!
      //4.
      testSwitch(null); // []
      testSwitch('yellow'); // ['banana', 'pineapple']
      testInsteadOfSwitch(null); // []
      testInsteadOfSwitch('yellow'); // ['banana', 'pineapple']

 

posted on 2024-07-26 18:11  技术高超  阅读(5)  评论(0编辑  收藏  举报