国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

如何讓你的JS代碼更好看易讀

2024-05-06 16:41:13
字體:
來源:轉載
供稿:網友

作為JS程序員,自己寫的代碼如果好看易讀,不只是自己看起來好看,在別的程序員接手以后,也會是交接工作異常順利。

不要在代碼中留大段注釋掉的代碼

留給git去管理,不然你要git干嘛

// bad// function add() {// const a = b + c// return a// }function add() { return a + 1000}// goodfunction add() { return a + 1000}

適當地換行

// badfunction a() { const { state_a, state_b, state_c } = this.state this.setState({state_a: state_a * 2}) return 'done'}// goodfunction a() { const { state_a, state_b, state_c } = this.state this.setState({state_a: state_a * 2}) return 'done'}

適當的添加注釋,但不要瘋狂的添加注釋

對一段代碼或者一行特別需要注意的代碼注釋

不要瘋狂的注釋,太啰嗦,漂亮的代碼自己會說話

// badconst a = 'a' // 這是aconst b = 'b' // 這是bconst c = 'c' // 這是c// good/** * 申明變量 */ const a = 'a' const b = 'b' const c = 'c'

將類似行為、命名的代碼歸類在一起

// badfunction handleClick(arr) { const a = 1 arr.map(e => e + a) const b = 2 return arr.length + b}// goodfunction 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() {}// badarr.map(a => { return add(a)})setTimeout(() => { doSomething()}, 1000)// goodarr.map(add)setTimeout(doSomething, 1000)

箭頭函數

// badconst a = (v) => { return v + 1}// goodconst a = v => v + 1// badconst b = (v, i) => { return { v, i }}// goodconst b = (v, i) => ({v, i})// badconst c = () => { return (dispatch) => { // doSomething }}// goodconst c = () => dispatch => { // doSomething}

提前對對象取值(寫react的同學一定懂)

// badconst a = this.props.prop_a + this.props.prop_bthis.props.fun()// goodconst { prop_a, prop_b, fun} = this.propsconst a = prop_a + prop_bfun()

合理使用各種表達式

// badif (cb) { cb()}// goodcb && cb()// badif (a) { return b} else { return c}// goodreturn a ? b : c// badif (a) { c = a} else { c = 'default'}// goodc = a || 'default'

鏈式調用寫法

// badfetch(url).then(res => { return res.json()}).then(() => { // doSomething}).catch(e => {})// goodfetch(url) .then(res => { return res.json() }) .then(() => { // doSomething }) .catch(e => { })

保持代碼是縱向發展的

發現那些在整個文件中特別'突出'的代碼時,應該考慮對他們做換行處理了

// badreturn handleClick(type, key, ref, self, source, props)// goodreturn handleClick( type, key, ref, self, source, props)// badconst a = this.props.prop_a === 'hello' ? <di>world</div> : null// goodconst a = this.props.prop_a === 'hello' ? <di>world</div> : null

 

 

注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长海县| 莫力| 吴堡县| 桐乡市| 贡山| 甘南县| 台湾省| 时尚| 昌黎县| 海阳市| 天长市| 嘉祥县| 监利县| 龙州县| 阳朔县| 高密市| 桑日县| 普定县| 汉寿县| 乌拉特中旗| 青海省| 巴南区| 蛟河市| 阳朔县| 青河县| 永修县| 西宁市| 同德县| 佳木斯市| 子长县| 太原市| 南京市| 黎城县| 图片| 新安县| 沧州市| 大新县| 宝兴县| 渭南市| 伽师县| 绥滨县|