10 个编写干净JavaScript 代码的最简单的技巧(适合初学者)

7a83742e2ed5944567d6a335af50a8f9.png

来源 | https://medium.com/frontend-canteen/10-simplest-tips-to-write-clean-javascript-code-for-beginners-8d52582b883

1、合并数组

正常代码:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);


console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"];

修改后的代码:

let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples];  // <-- here


console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"];
let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒'];  // <-- here


console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"];

2、 从数组中获取值

正常代码:

let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];


console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏;

使用数组解构的干净代码:

let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples;  // <-- here


console.log( redApple );    //=> 🍎
console.log( greenApple );  //=> 🍏;

3、从对象中获取价值

正常代码:

let user = {
  "name": "bytefish",
  "age": 99
}


let name = user.name
let age = user.age


console.log( name );
console.log( age );;

使用对象解构的干净代码:

let user = {
  "name": "bytefish",
  "age": 99
}


let {name, age} = user


console.log( name );
console.log( age );;

4、循环数组

正常代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];


for (let i = 0; i < fruits.length; i++){
  console.log(fruits[i])
};

使用 for of 后的代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];


for (fruit of fruits) {
  console.log(fruit)
};

5、使用箭头函数作为回调

正常代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];


// Using forEach method
fruits.forEach(function(fruit){
  console.log( fruit );
});;

使用箭头函数清理代码:

let fruits = ['🍉', '🍊', '🍇', '🍎'];
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') {  //=> 🍎


      // 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')
};

总结

以上就是我今天跟你分享的10个简单编写JavaScript的技巧,希望对你有用。

学习更多技能

请点击下方公众号

d7168c78b8c0716f65b6547099b673c9.gif

c6ff0903697ab92f433c872764dc39cc.png

ea2f21531cb1dcdac82f5bdd4303f46f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值