写出更好代码的5个js技巧

写出更好代码的5个js技巧

1. 使用 .map 或者 .forEach 代替 for 遍历

const numbers = [1, 2, 3, 4, 5, 6, 7, 8]

// DON'T
for (i = 0; i < numbers.length; i++) {
     
  console.log(i); // 1, 2, 3, 4, 5, 6, 7, 8
}

// DO

numbers.map(number => console.log(number)); // 1, 2, 3, 4, 5, 6, 7, 8

// OR 

numbers.forEach(number => console.log(number)); // 1, 2, 3, 4, 5, 6, 7, 8

上面的代码循环数字并打印输出每个数字

但是如果我们有更复杂的数组呢,例如对象数组?使用 map,filter,reduce 遍历

const dogs = [
  {
      name: "Sam", age: 2, owner: "Jack"},
  {
      name: "Simon", age: 8, owner: "Trevor"}
]

// DO
dogs.map(dog => console.log(dog))

// DON'T
 for (let dog of dogs) {
     
   console.log(dog)
 }

forEach,map,reduce,filter 是方法,只能用于数组

const dogs = {
      
  name: "Sam",
  age: 10,
}

// ERROR: "TypeError: dogs.map is not a function"
// Won't work since map can only called on arrays.
dogs.map(dog => console.log(dog))

遍历对象,用 for ... in

const dogs = {
      
  name: "Sam",
  age: 10,
 }

// Looping over objects

for (let prop in dogs) {
     
  console.log(prop); // "name", "age"
}

更好的遍历对象方法如下:

  • Object.keys
  • Object.values
  • Object.enries

2. 默认使用 const

const 定义的是不可变量,let 声明可以变的变量

默认声明的遍历不可用,防止出现

3. 避免嵌套闭包

闭包js的精髓

const names = ["Indrek", "Trevor", "Anna", "Buck"]

const lowerCaseNames = names.map(name => {
     
 return name.toLowerCase()
})

console.log(lowerCaseNames); // ["indrek", "trevor", "anna", "buck"]

发现闭包了吗?在第4行

避免嵌套闭包

const names = ["Indrek", "Trevor", "Anna", "Buck"]

const namesToLowerCase = name => name.toLowerCase()

const lowerCaseNames = names.map(namesToLowerCase)

console.log(lowerCaseNames); // ["indrek", "trevor", "anna", "buck"]

我们将闭包放到函数表达式中。通过这种方式,我们的代码更容易理解和推理。下面是代码示例。

const students = [
  {
     
    name: "Indrek",
    score: 33.99
  },
  {
     
    name: "John",
    score: 50.35
  },
  {
     
    name: "Alice",
    score: 63.35
  }
];
                

const calcAverageScore = students.reduce((accumulator, currentValue) => {
     
	  return Math.round(accumulator + currentValue.score)
}, 0)

console.log(calcAverageScore); // 147

下面介绍如何通过简单地将分数求和逻辑提取出来作为函数表达式来改进代码。

const students = [
  {
     
    name: "Indrek",
    score: 33.99
  },
  {
     
    name: "John",
    score: 50.35
  },
  {
     
    name: "Alice",
    score: 63.35
  }
];
                

const addScores = (accumulator, currentValue) => Math.round(accumulator + currentValue.score)

const calcAverageScore = students.reduce(addScores, 0)

console.log(calcAverageScore); // 147

4. 避免嵌套 if

嵌套 if 语句的地方都可以闻到坏代码的味道

eg: 幼稚的写法

if (hasName) {
     
  if (hasSurname) {
     
    if (favouriteDrink === "water") {
     
      console.log(hasName, hasSurname, favouriteDrink)
    }
  }
}

花点时间优化下面的代码

if (hasName && hasSurname && favouriteDrink === "water") {
     
  console.log(hasName, hasSurname, favouriteDrink)
}

5. 用变量代替复杂的 if 子句

const person = {
     
  name: "Indrek",
  age: 26,
  pets: {
     
    name: "Simmo",
    type: "cat",
    age: 8.5
  }
}

if (person.name === "Indrek" && person.age === 26 && person.pets && person.pets.type === "cat") {
     
 console.log("You're definitely Indrek")
}

更好的写法

const person = {
     
  name: "Indrek",
  age: 26,
  pets: {
     
    name: "Simmo",
    type: "cat",
    age: 8.5
  }
}

const isIndrek = person.name === "Indrek" && person.age === 26 
const hasPets = person.pets && person.pets.type === "cat"

if (isIndrek && hasPets) {
     
 console.log("You're definitely Indrek")
}

你可能感兴趣的:(JavaScript,javascript)