js中一些【小而美】的编写优雅代码的方法

撸码一年有余,渐渐的开始注意代码规范与代码质量,在看别人的代码中慢慢学习积累各种小而美的写法使代码优雅健壮。

三目运算

bad

const num = 20;
let str;
if (num > 10) {
    str = 'is greater';
} else {
    str = 'is lesser';
}

good

const num = 20;
let str = num>10 ? 'a':'b'

短路运算

在很多情况下可能会对某些参数进行判断来增加函数的健壮性

bad

let tem=null;
if (params !== null || params !== undefined || params !== '') {
     tem = params;
}else{
    tem='init'
}

good

let tem = params || ''init"

if判断某个变量是否为true时

bad

let likeJavaScript
if (likeJavaScript === true){
  console.log("hello world")
}

good

let likeJavaScript
if (likeJavaScript){
}

此写法须注意条件参数在做类型转换时是否为true

十进制指数

当需要写数字带有很多零时(如10000000),可以采用指数(1e7)来代替这个数字

bad

let i=1000000

good

let i=1e7

对象属性简写

如果属性名与key名相同,则可以采用ES6的方法: const obj = { x:x, y:y };

bad

const obj={
  x:x,
  y:y
}

good

const obj={
  x,
  y
}

箭头函数简写

foo的传统写法固然是非常直观的能让人理解,但是在将函数作为参数传递的过程中就不是十分优雅了,而箭头函数就能良好的展示函参关系

bad

list.forEach(function(item) {
 console.log(item.name); 
});

good

list.forEach(item=>console.log(item));

箭头函数简写

foo的传统写法固然是非常直观的能让人理解,但是在将函数作为参数传递的过程中就不是十分优雅了,而箭头函数就能良好的展示函参关系

bad

list.forEach(function(item) {
 console.log(item.name); 
});

good

list.forEach(item=>console.log(item));

箭头函数内的隐式返回值简写

在箭头函数内有返回值时省略不必要的return

bad

const foo = () =>{
  return 111  
}

good

const foo = () =>(111)

给函数设置默认参数值

bad

function temFoo(a,b,c){
  a = a||0;
  b = b||0;
  c = c||0;
}

good

function temFoo(a=0,b=0,c=0){
  //...
}

解构赋值的简写方法

在平时的业务中,经常需要在组件和API中传递数组或对象字面量的数据,

bad

const store = this.props.store; const form = this.props.form; 
const loading = this.props.loading; const errors = this.props.errors;
const entity = this.props.entity;

good

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;

扩展运算符简写

bad

// joining arrays 
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays 
const arr = [1, 2, 3, 4]; 
const arr2 = arr.slice()

good

// joining arrays 
const odd = [1, 3, 5 ]; 
const nums = [2 ,4 , 6, ...odd]; 
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]
// cloning arrays 
const arr = [1, 2, 3, 4]; 
const arr2 = [...arr];

强制参数简写

我们在编写某些函数时,有些参数是必传项,但是可能调用的同学没有传递该参数,我们一般会抛出异常

bad

function foo(bar) { 
  if(bar === undefined) { 
    throw new Error('Missing parameter!'); 
  } 
  return bar; 
}

good

mandatory = () => {
  throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
  return bar;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,221评论 0 13
  • 更合理的方式写 JavaScript 原文看 这里 ,收录在此为便于查阅。 类型 1.1 基本类型:直接存取。字符...
    杀破狼real阅读 8,849评论 0 6
  • 函数参数的默认值 基本用法 在ES6之前,不能直接为函数的参数指定默认值,只能采用变通的方法。 上面代码检查函数l...
    呼呼哥阅读 3,497评论 0 1
  • 大宝打电话过来时,正和新房的设计师交流。之前量房的时候是零交流,所以设计出来的图纸也就很不满意。等我打完电话,设计...
    鹰飞飞阅读 149评论 0 1
  • 灵魂是座孤独的城, 不知道要去向何方。 爱是绵绵不朽的永恒。 但愿您依旧在我生命的下一秒, 现实是遮着尘土的眼睛,...
    素颜之爱情独角戏阅读 324评论 0 0