10 个编写干净JavaScript 代码的最简单的技巧(适合初学者)
1、合并数组
正常代码:
let apples = ['redApple', 'greenApple'];
let fruits = ['watermelon', 'strawberry', 'grape'].concat(apples);
console.log( fruits );
//=> ["watermelon", "strawberry", "grape", "redApple", "greenApple"];修改后的代码:
let apples = ['redApple', 'greenApple'];
let fruits = ['watermelon', 'strawberry', 'grape', ...apples];  // <-- here
console.log( fruits );
//=> ["watermelon", "strawberry", "grape", "redApple", "greenApple"];
let apples = ['redApple', 'greenApple'];
let fruits = [...apples, 'banana', 'cherry'];  // <-- here
console.log( fruits );
//=> ["redApple", "greenApple", "banna", "cherry"];2、 从数组中获取值
正常代码:
let apples = ['redApple', 'greenApple'];
let redApple = apples[0];
let greenApple = apples[1];
console.log( redApple );    //=> redApple
console.log( greenApple );  //=> greenApple;使用数组解构的干净代码:
let apples = ['redApple', 'greenApple'];
let [redApple, greenApple] = apples;  // <-- here
console.log( redApple );    //=> redApple
console.log( greenApple );  //=> greenApple;3、从对象中获取价值
正常代码:
let user = {
  "name": "SJAY",
  "age": 18
}
let name = user.name
let age = user.age
console.log( name ); // => SJAY
console.log( age );  // => 18使用对象解构的干净代码:
let user = {
  "name": "SJAY",
  "age": 18
}
let {name, age} = user
console.log( name ); // => SJAY
console.log( age ); // => 18
4、循环数组
正常代码:
let fruits = ['watermelon', 'strawberry', 'grape', 'redApple'];
for (let i = 0; i < fruits.length; i++){
  console.log(fruits[i])
};使用 for of 后的代码:
let fruits = ['watermelon', 'strawberry', 'grape', 'redApple'];
for (fruit of fruits) {
  console.log(fruit)
};5、使用箭头函数作为回调
正常代码:
let fruits = ['watermelon', 'strawberry', 'grape', 'redApple'];
// Using forEach method
fruits.forEach(function(fruit){
  console.log( fruit );
});使用箭头函数清理代码:
let fruits = ['watermelon', 'strawberry', 'grape', 'redApple'];
fruits.forEach(fruit => console.log( fruit ));注意:在处理这个时,箭头函数与普通函数不同。如果你在你的函数中使用它,不要贸然替换它。
6、在数组中查找一项
假设我们需要通过一个对象的属性从一个对象数组中查找一个对象,我们通常使用 for 循环:
let inventory = [
  {name: 'Bananas', quantity: 5},
  {name: 'Apples', quantity: 10},
  {name: 'Grapes', quantity: 2}
];
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  for (let index = 0; index < arr.length; index++) {
    // Check the value of this object property `name` is same as 'Apples'
    if (arr[index].name === 'Apples') {  //=> redApple
      // A match was found, return this object
      return arr[index];
    }
  }
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 };使用 array.find() 清理代码:
let inventory = [
  {name: 'Bananas', quantity: 5},
  {name: 'Apples', quantity: 10},
  {name: 'Grapes', quantity: 2}
];
// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  return arr.find(obj => obj.name === 'Apples');  // <-- here
}
let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 };7、将字符串转换为数字
正常代码:
let num = parseInt("10")
console.log( num )         //=> 10
console.log( typeof num )  //=> "number";通过在字符串前添加 + 来清理代码:
let num = +"10";
console.log( num )           //=> 10
console.log( typeof num )    //=> "number"
console.log( +"10" === 10 )  //=> true;
8、检查无效
在使用变量之前,我们经常需要检查其值是否为空。
正常的方法是使用 if-else。function getUserRole(role) {
  let userRole;
// If role is not falsy value
  // set userRole as passed role value
  if (role) {
userRole = role;} else {
// else set the `userRole` as USER
userRole = 'USER';}
return userRole;
}
console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN";
使用 || 清理代码 :function getUserRole(role) {
  return role || 'USER';  // <-- here
}
console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN";
9、字符串连接
正常代码:let name = 'bytefish';
let message = 'Hi '+ name + '!';
使用模板文字清洁代码:
let name = 'bytefish';
let message = `Hi ${name}!`;10、使用速记
正常代码:
let x = 1
if (x !== '' && x !== null && x !== undefined) {
  console.log('x is not nullish')
};使用速记运算符清洁代码:
let x = 1
if (!!x){
  console.log('x is not nullish')
};本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭