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 literalfunction 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;}, [[], []]);