JavaScript(ES6) 中条件语句

1.使用 Array.includes 来处理多个条件

function test(fruit) {
  if (fruit == 'apple' || fruit == 'strawberry') {
    console.log('red');
  }
}

优化变成 ->>

function test(fruit) {
  // 条件提取到数组中
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
 
  if (redFruits.includes(fruit)) {
    console.log('red');
  }
}

2.减少嵌套,提前使用 return 语句

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
 
  // 条件 1:fruit 必须有值
  if (fruit) {
    // 条件 2:必须为红色
    if (redFruits.includes(fruit)) {
      console.log('red');
 
      // 条件 3:数量必须大于 10
      if (quantity > 10) {
        console.log('big quantity');
      }
    }
  } else {
    throw new Error('No fruit!');
  }
}
 
// 测试结果
test(null); // 抛出错误:No fruits
test('apple'); // 打印:red
test('apple', 20); // 打印:red,big quantity

优化

/* 在发现无效条件时提前 return */
 
function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
 
  // 条件 1:提前抛出错误
  if (!fruit) throw new Error('No fruit!');
 
  // 条件2:必须为红色
  if (redFruits.includes(fruit)) {
    console.log('red');
 
    // 条件 3:数量必须大于 10
    if (quantity > 10) {
      console.log('big quantity');
    }
  }
}

为了减少一个嵌套层级,优化编码风格

/* 在发现无效条件时提前 return */
 
function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
 
  if (!fruit) throw new Error('No fruit!'); // 条件 1:提前抛出错误
  if (!redFruits.includes(fruit)) return;  // 条件 2:当 fruit 不是红色的时候,提前 return
 
  console.log('red');
 
  // 条件 3:必须是大量存在
  if (quantity > 10) {
    console.log('big quantity');
  }
}

3.使用函数的默认参数 和 解构

function test(fruit, quantity) {
  if (!fruit) return;
  const q = quantity || 1; // 如果没有提供 quantity 参数,则默认为 1
 
  console.log(`We have ${q} ${fruit}!`);
}
 
// 测试结果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!

但是q在这边不直观所有优化

function test(fruit, quantity = 1) { // i如果没有提供 quantity 参数,则默认为 1
  if (!fruit) return;
  console.log(`We have ${quantity} ${fruit}!`);
}
 
// 测试结果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!

但是这边 也可能是个对象

// 解构 —— 只获得 name 属性
// 参数默认分配空对象 {}
function test({name} = {}) {
  console.log (name || 'unknown');
}
 
//测试结果
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

4.选择 Map / Object 字面量,而不是Switch语句

function test(color) {
  // 使用 switch case 语句,根据颜色找出对应的水果
  switch (color) {
    case 'red':
      return ['apple', 'strawberry'];
    case 'yellow':
      return ['banana', 'pineapple'];
    case 'purple':
      return ['grape', 'plum'];
    default:
      return [];
  }
}
 
//测试结果
test(null); // []
test('yellow'); // ['banana', 'pineapple']

这边建议使用对象,更加清晰

// 使用对象字面量,根据颜色找出对应的水果
  const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
  };
 
function test(color) {
  return fruitColor[color] || [];
}

但是这边是很有可能为网络数据,无法判断red这样的变量,那么就用arry.filter 来过滤

const fruits = [
    { name: 'apple', color: 'red' }, 
    { name: 'strawberry', color: 'red' }, 
    { name: 'banana', color: 'yellow' }, 
    { name: 'pineapple', color: 'yellow' }, 
    { name: 'grape', color: 'purple' }, 
    { name: 'plum', color: 'purple' }
];
 
function test(color) {
  // 使用 Array filter  ,根据颜色找出对应的水果
 
  return fruits.filter(f => f.color == color);
}

5.使用 Array.every 和 Array.some 来处理全部/部分满足条件

我们想检查所有水果是否都是红色的

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];
 
function test() {
  let isAllRed = true;
 
  // 条件:所有的水果都必须是红色
  for (let f of fruits) {
    if (!isAllRed) break;
    isAllRed = (f.color == 'red');
  }
 
  console.log(isAllRed); // false
}

使用 arry.every来过滤

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];
 
function test() {
  // 条件:简短方式,所有的水果都必须是红色
  const isAllRed = fruits.every(f => f.color == 'red');
 
  console.log(isAllRed); // false
}

如果我们想要检查是否有至少一个水果是红色的,我们可以使用 Array.some 仅用一行代码就实现出来

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
];
 
function test() {
  // 条件:是否存在红色的水果
  const isAnyRed = fruits.some(f => f.color == 'red');
 
  console.log(isAnyRed); // true
}

出自 https://juejin.im/entry/5bd7af3a6fb9a05d0e2eb15e?from=timeline

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值