# 1. 使用对象代替条件 if 判断

在某些条件下,我们需要根据变量的值来调用不同的函数或者赋值。一般我们遇到这种情况可能会写大量的 if 条件判断块,但是大量的 if 代码不利于代码阅读和理解,有些时候我们可以使用对象来解决此问题。

像以下例子中,使用了大量的 if else 判断条件,使得代码变得难以理解。

function func(type) {
  if (type == 'a') {
    return 1;
  } else if (type == 'b') {
    return 2;
  } else if (type == 'c') {
    return 3;
  } else {
    return 4;
  }
}

我们可以将上述例子重构:

function func(type) {
  const objType = {
    a: 1,
    b: 2,
    c: 3,
    default: 4
  }
  return objType[type] || objType.default
}

上述方法不仅仅可以重构 if else 语句,也可以重构 switch case 语句:

function func(type) {
  switch(type) {
    case 'a':
      func1();
      break;
    case 'b':
      func2();
      break;
    case 'c':
      func3();
      break;
    default:
      func4();
      break;
  }
}

上述的 switch case 例子我们可以重构为:

function func(type) {
  const obj = {
    a: func1(),
    b: func2(),
    c: func3(),
    default: func4()
  }
  return obj[type]() || obj.default();
}

上述这些例子中,如果对象不需要更改的话,我们可以将它移动到更高的作用域范围中。上述的这些情况可能只适合一些简单的情况,对于一些复杂的情况可能并不适合,不能盲目的使用。

# 2. 其他使用对象的例子

当我们有需求查找一个数组中出现最多次数的元素时,我们可能会这么做:

function findMaxItem() {
  const arr = [1,2,5,2,1,3,5,6,8,5,9,10,11,2,4]
  let max = {value: '', times: 0};
  for (let i in arr) {
    cosnt time = list.filter(item => item === i).length;
    if (time > max.times) {
      max = {value: i, times: time};
    }
  }
  return max;
}

上述的例子中我们嵌套了一次循环才得到列表中出现最多的元素,因为这里嵌套一次循环,所以这个例子在事件上的复杂度是 O (n²) ,试想下,如果数据量很大的情况下这种方法很显然不够好!我们可以将上述方法重构如下:

function findMaxItem() {
  const arr = [1,2,5,2,1,3,5,6,8,5,9,10,11,2,4]
  const itemList = {};
  let max = {value: '', times: 0};
  for (let i in arr) {
    itemList[i] = (itemList[i] || 0) + 1;
  }
  for (let i of Object.keys(itemList)) {
    if (itemList[i] > max.times) {
      max = {value: i, times: itemList[i]};
    }
  }
}

上述例子中,虽然我们有两个循环,但是却不是嵌套的相比于之前的嵌套循环,我们重构后的例子更加的合理,事件复杂度也是 O (n)。因此重构后的例子性能上更加的出众!

上述的例子,只是开发中的一些小技巧,希望你能喜欢。javascript 开发中还有很多便捷开发的小技巧,也希望你能提出你在日常开发中的一些简洁的操作!

# js 删除对象里的某个属性

# 使用 delete

let a = {b:1,c:2}
delete a.b//true
console.log(a)//{c:2}

# 2 使用解构

let a = {b:1,c:2}
let {b,...a} = a
console.log(a)//{c:2}

# 使用反射

let a = {b:1,c:2}
Reflect.deleteProperty(a,"b");
console.log(a)//{c:2}