JavaScript 的几个小技巧

1. 尽早 return

function transformData(rawData) {
  // check if no data
  if (!rawData) {
    return [];
  }

  // actual function code goes here
  return rawData.map((item) => item);
}

将无效的用例尽早返回,避免意外和不必要的代码处理。

2. 用对象映射方式替代分支语句

function getDrink (type) {
  if (type === 'coke') {
    type = 'Coke';
  } else if (type === 'pepsi') {
    type = 'Pepsi';
  } else if (type === 'lemonade') {
    type = 'Lemonade';
  } else if (type === 'fanta') {
    type = 'Fanta';
  } else {
    // acts as our "default"
    type = 'Unknown drink!';
  }
  return 'You\'ve picked a ' + type;
}

// Object literal
function getDrink (type) {
  var drinks = {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade',
    'default': 'Default item'
  };
  return 'The drink I chose was ' + (drinks[type] || drinks['default']);
}
  • 分支语句的处理方式导致函数代码量大,要覆盖所有的逻辑分支。
  • 要添加一种新的 type 就需要再添加一个分支判断

3. 多重判断时使用 Array.includes 或者 !~Array.indexOf(),避免过长逻辑判断

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

// ----- 改进后 ------
function testFun(fruit) {
  const fruits = ['apple', 'strawberry', 'cherry'];
  if (redFruits.includes(fruit)) {
    console.log('red');
  }
   
  // if (!~redFruits.indexOf(fruit)) {
  //   console.log('red');
  // }
}

4. 一次循环两个数组

const exampleValues = [2, 15, 8, 23, 1, 32];
const [truthyValues, falseyValues] = exampleValues.reduce((arrays, exampleValue) => {
  if (exampleValue > 10) {
    arrays[0].push(exampleValue);
    return arrays;
  }

  arrays[1].push(exampleValue);
  return arrays;
}, [[], []]);
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容