作为JS程序员,自己写的代码如果好看易读,不只是自己看起来好看,在别的程序员接手以后,也会是交接工作异常顺利。
不要在代码中留大段注释掉的代码
留给git去管理,不然你要git干嘛
// bad // function add() { // const a = b + c // return a // } function add() { return a + 1000 } // good function add() { return a + 1000 }
适当地换行
// bad function a() { const { state_a, state_b, state_c } = this.state this.setState({state_a: state_a * 2}) return 'done' } // good function a() { const { state_a, state_b, state_c } = this.state this.setState({state_a: state_a * 2}) return 'done' }
适当的添加注释,但不要疯狂的添加注释
对一段代码或者一行特别需要注意的代码注释
不要疯狂的注释,太啰嗦,漂亮的代码自己会说话
// bad const a = 'a' // 这是a const b = 'b' // 这是b const c = 'c' // 这是c // good /** * 申明变量 */ const a = 'a' const b = 'b' const c = 'c'
将类似行为、命名的代码归类在一起
// bad function handleClick(arr) { const a = 1 arr.map(e => e + a) const b = 2 return arr.length + b } // good function handleClick(arr) { const a = 1 const b = 2 arr.map(e => e + a) return arr.length + b }
在不破坏语义性的情况下,'能省则省'
牢记js中函数是一等公民
但是,如果省略到影响可读性了,就是失败的
在可读性和简洁性至今必须选一个的话,永远先选可读性
function add(a) { return a + 1 } function doSomething() { } // bad arr.map(a => { return add(a) }) setTimeout(() => { doSomething() }, 1000) // good arr.map(add) setTimeout(doSomething, 1000)
箭头函数
// bad const a = (v) => { return v + 1 } // good const a = v => v + 1 // bad const b = (v, i) => { return { v, i } } // good const b = (v, i) => ({v, i}) // bad const c = () => { return (dispatch) => { // doSomething } } // good const c = () => dispatch => { // doSomething }
提前对对象取值(写react的同学一定懂)
// bad const a = this.props.prop_a + this.props.prop_b this.props.fun() // good const { prop_a, prop_b, fun } = this.props const a = prop_a + prop_b fun()
合理使用各种表达式
// bad if (cb) { cb() } // good cb && cb() // bad if (a) { return b } else { return c } // good return a "htmlcode">// bad fetch(url).then(res => { return res.json() }).then(() => { // doSomething }).catch(e => { }) // good fetch(url) .then(res => { return res.json() }) .then(() => { // doSomething }) .catch(e => { })保持代码是纵向发展的
发现那些在整个文件中特别'突出'的代码时,应该考虑对他们做换行处理了
// bad return handleClick(type, key, ref, self, source, props) // good return handleClick( type, key, ref, self, source, props ) // bad const a = this.props.prop_a === 'hello' ? <di>world</div> : null // good const a = this.props.prop_a === 'hello' ? <di>world</div> : null
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 《星舰铳犬太阳系物语》游戏背景介绍
- 《战锤40K星际战士2》终极版有后续DLC说明
- 《第9层》游戏特色玩法介绍
- 刀郎.2006-刀郎【九雨天下】【WAV+CUE】
- 59.9高校生.1994-素兰万岁【上华】【WAV+CUE】
- ECHO.1991-你是爱我还是需要我(国专)【EMI百代】【WAV+CUE】
- 交错战线零课主线困难通关阵容推荐一览
- 交错战线挖掘矿场角色推荐攻略
- 命运圣契公测平民阵容怎么搭配 新手开荒平民阵容攻略
- 金梅《现代发烧的声音2》发烧碟[WAV+CUE]
- 雨果唱片-《历史录音珍藏系列-现代芭蕾舞剧·红色娘子军》2CD【WAV】
- [雨果唱片]李冰《地方民歌·戏曲系列-爱的颂歌》WAV
- 《模拟人生》真人电影官宣!玛格特·罗比担任制片人
- 《星战绝地》系列玩家数超4000万!续作表现超预期
- EA称AI是其业务核心!能提高开发效率、节约成本