寫更漂亮的javascript

用更合理的方式寫 JavaScript

目錄

  1. 聲明變量
  2. 對象
  3. 數組
  4. 字符串
  5. 函數
  6. 箭頭函數
  7. 模塊
  8. 迭代器和生成器
  9. 屬性
  10. 變量
  11. 提升
  12. 比較運算符和等號
  13. 代碼塊
  14. 注釋
  15. 空白
  16. 逗號
  17. 分號
  18. 類型轉換
  19. 命名規則

聲明變量

  • 1.1 使用let和const代替var
    • 不會變的聲明用const
    //bad 
    var $cat = $('.cat')//good
    const $cat = $('.cat')
    
    • 會變動的聲明用let
    //bad 
    var count = 1
    if (count<10) {count += 1
    }//good
    let count = 1
    if (count<10) {count += 1
    }
    
  • 1.2 將所有的 constlet 分組

    為什么?當你需要把已賦值變量賦值給未賦值變量時非常有用。

    // bad
    let i, len, dragonball,items = getItems(),goSportsTeam = true;// bad
    let i;
    const items = getItems();
    let dragonball;
    const goSportsTeam = true;
    let len;// good
    const goSportsTeam = true;
    const items = getItems();
    let dragonball;
    let i;
    let length;
  • 1.3 在你需要的地方給變量賦值,但請把它們放在一個合理的位置。

    為什么?letconst 是塊級作用域而不是函數作用域。

    // bad - unnecessary function call
    const checkName = function (hasName) {const name = getName();if (hasName === 'test') {return false;}if (name === 'test') {this.setName('');return false;}return name;
    };// good
    const checkName = function (hasName) {if (hasName === 'test') {return false;}const name = getName();if (name === 'test') {this.setName('');return false;}return name;
    };

    ? 返回目錄

對象 Objects

  • 2.2 創建有動態屬性名的對象時,使用可被計算的屬性名稱。

    為什么?因為這樣可以讓你在一個地方定義所有的對象屬性。

    const getKey = function (k) {return `a key named ${k}`;
    };// bad
    const obj = {id: 1,name: 'San Francisco',
    };
    obj[getKey('enabled')] = true;// good
    const obj = {id: 1,name: 'San Francisco',[getKey('enabled')]: true,
    };

數組 Arrays

? 返回目錄

字符串 Strings

  • 4.5 不要在字符串中使用 eval(),這個方法有要多缺陷。eslint: no-eval

? 返回目錄

函數 Functions

  • 5.6 直接給函數的參數指定默認值,不要使用一個變化的函數參數。

    // really bad
    const handleThings = function (opts) {// 不!我們不應該改變函數參數。// 更加糟糕: 如果參數 opts 是 false 的話,它就會被設定為一個對象。// 但這樣的寫法會造成一些 Bugs。//(譯注:例如當 opts 被賦值為空字符串,opts 仍然會被下一行代碼設定為一個空對象。)opts = opts || {};// ...
    };// still bad
    const handleThings = function (opts) {if (opts === void 0) {opts = {};}// ...
    };// good
    const handleThings = function (opts = {}) {// ...
    };
  • 5.7 直接給函數參數賦值時需要避免副作用。

    為什么?因為這樣的寫法讓人感到很困惑。

    var b = 1;
    // bad
    const count = function (a = b++) {console.log(a);
    };
    count();  // 1
    count();  // 2
    count(3); // 3
    count();  // 3

  • 5.10 優先使用擴展運算符 ... 來調用參數可變的函數。 eslint: prefer-spread

    為什么? 這樣寫代碼更干凈,不必提供上下文。

    ```javascript
    // bad
    const x = [1, 2, 3, 4, 5];
    console.log.apply(console, x);

    // good
    const x = [1, 2, 3, 4, 5];
    console.log(...x);

    // bad
    new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));

    // good
    new Date(...[2016, 8, 5]);

? 返回目錄

箭頭函數

? 返回目錄

模塊 Modules

  • 7.1 總是使用模組 (import/export) 而不是其他非標準模塊系統。你可以編譯為你喜歡的模塊系統。

    為什么?模塊化是未來趨勢。

    // bad
    const AirbnbStyleGuide = require('./AirbnbStyleGuide');
    module.exports = AirbnbStyleGuide.es6;// ok
    import AirbnbStyleGuide from './AirbnbStyleGuide';
    export default AirbnbStyleGuide.es6;// best
    import {es6} from './AirbnbStyleGuide';
    export default es6;
  • 7.2 不要使用通配符 import。

    為什么?這樣能確保你只有一個默認 export。

    // bad
    import * as AirbnbStyleGuide from './AirbnbStyleGuide';// good
    import AirbnbStyleGuide from './AirbnbStyleGuide';
  • 7.3 不要從 import 中直接 export。

    為什么?雖然一行代碼簡潔明了,但讓 import 和 export 各司其職讓事情能保持一致。

    // bad
    // filename es6.js
    export {es6 as default} from './airbnbStyleGuide';// good
    // filename es6.js
    import {es6} from './AirbnbStyleGuide';
    export default es6;

  • 7.4 不要多次 import 同一個文件。eslint: no-duplicate-imports

    Why? 多個地方引入同一個文件會使代碼難以維護。

    // bad
    import foo from 'foo';
    // … some other imports … //
    import {named1, named2} from 'foo';// good
    import foo, {named1, named2} from 'foo';// good
    import foo, {named1,named2,
    } from 'foo';

? 返回目錄

Iterators and Generators

? 返回目錄

屬性 Properties

? 返回目錄

變量 Variables

  • 11.1 不要鏈式的給變量賦值。eslint: no-multi-assign

    為什么?鏈式變量賦值會創建隱式的全局變量。

    // bad
    (function example() {// JavaScript interprets this as// let a = ( b = ( c = 1 ) );// The let keyword only applies to variable a; variables b and c become// global variables.let cat = dog = bird = 1;
    }());console.log(cat); // throws ReferenceError
    console.log(dog); // 1
    console.log(bird); // 1// good
    (function example() {let cat = 1;let dog = cat;let bird = cat;
    }());console.log(cat); // throws ReferenceError
    console.log(dogb); // throws ReferenceError
    console.log(bird); // throws ReferenceError// the same applies for `const`

  • 10.2 避免使用累加和累減符號 (++, --)。 eslint no-plusplus

    為什么?根據 eslint 文檔,累加和累減會受到自動插入分號的影響,并可能導致一些意外情況發生。

    // bad
    const array = [1, 2, 3];
    let num = 1;
    num++;
    --num;let sum = 0;
    let truthyCount = 0;
    for (let i = 0; i < array.length; i++) {let value = array[i];sum += value;if (value) {truthyCount++;}
    }// good
    const array = [1, 2, 3];
    let num = 1;
    num += 1;
    num -= 1;const sum = array.reduce((a, b) => a + b, 0);
    const truthyCount = array.filter(Boolean).length;

  • 10.3 避免使用魔法數字(白名單如下)。 eslint no-magic-numbers

    為什么?魔法數字讓人難難以明白開發者的意圖是什么,破壞代碼的可讀性和可維護性。

    // 以下為魔法數字白名單
    let magicNumberIgnore = [];// baisc number
    magicNumberIgnore = magicNumberIgnore.concat([-1, 0, 100, 1000, 10000
    ]);// datetime number
    magicNumberIgnore = magicNumberIgnore.concat([12, 24, 60, 3600
    ]);// httpcode number
    magicNumberIgnore = magicNumberIgnore.concat([200,301, 302, 303, 304,400, 401, 402, 403, 404,500, 501, 502, 503, 504
    ]);// bit number
    magicNumberIgnore = magicNumberIgnore.concat([1024
    ]);// number 1-49
    for (i = 1; i <= 49; i++) {if (magicNumberIgnore.indexOf(i) === -1) {magicNumberIgnore.push(i);}}
    // bad
    let soldNum = 102;
    let initNum = 80;// good
    const APPLE = 102;
    const STOCK = 80;
    let soldNum = APPLE;
    let initNum = STOCK;

? 返回目錄

Hoisting

? 返回目錄

比較運算符和等號

  • 12.1 使用 ===!== 而不是 ==!=。eslint: eqeqeq

  • 12.2 條件表達式例如 if 語句通過抽象方法 ToBoolean 強制計算它們的表達式并且總是遵守下面的規則:

    • 對象 被計算為 true
    • Undefined 被計算為 false
    • Null 被計算為 false
    • 布爾值 被計算為 布爾的值
    • 數字 如果是 +0、-0、或 NaN 被計算為 false, 否則為 true
    • 字符串 如果是空字符串 '' 被計算為 false,否則為 true
    if ([0] && []) {// true// an array (even an empty one) is an object, objects will evaluate to true
    }
  • 12.3 布爾值使用簡寫,但是需要顯示比較字符串和數字。

    // bad
    if (isValid === true) {// ...
    }// good
    if (isValid) {// ...
    }// bad
    if (name) {// ...
    }// good
    if (name !== '') {// ...
    }// bad
    if (collection.length) {// ...
    }// good
    if (collection.length > 0) {// ...
    }
  • 12.4 想了解更多信息,參考 Angus Croll 的 Truth Equality and JavaScript。

  • 12.5 當 casedefault 包含的子句中有詞法聲明時,用大括號包裹。(例如 let, const, function, and class). eslint: no-case-declarations

    為什么?詞法聲明在整個 switch 塊中是可見的,但只有在代碼執行到 case 中變量被賦值時才會被初始化,當多個 case 子句中定義相同的變量是時會出現問題。

    // bad
    switch (foo) {case 1:let xx = 1;break;case 2:const yy = 2;break;case 3:const func = function () {// ...};break;default:get();
    }// good
    switch (foo) {case 1: {let xx = 1;break;}case 2: {const yy = 2;break;}case 3: {const func = function () {// ...};break;}case 4:bar();break;default: {get();}
    }

  • 12.6 三元表達式不能嵌套使用。 eslint: no-nested-ternary

    // bad
    const foo = maybe1 > maybe2? "bar": value1 > value2 ? "baz" : null;// split into 2 separated ternary expressions
    const maybeNull = value1 > value2 ? 'baz' : null;// better
    const foo = maybe1 > maybe2? 'bar': maybeNull;// best
    const foo = maybe1 > maybe2 ? 'bar' : maybeNull;

  • 12.7 避免出現不必要的三元表達式。 eslint: no-unneeded-ternary

    // bad
    const foo = maybe1 ? maybe1 : maybe2;
    const bar = correct ? true : false;
    const baz = wrong ? false : true;// good
    const foo = maybe1 || maybe2;
    const bar = !!correct;
    const baz = !wrong;

  • 12.8 當混用操作符時,要用括號括起來。唯一的例外是標準的算術運算符 (+, -, *, & /),因為它們很容易理解。 eslint: no-mixed-operators

    為什么?這提高了代碼的可讀性,并且使得開發者的意圖很清晰。

    // bad
    const foo = p1 && p2 < 0 || p3 > 0 || p4 + 1 === 0;// bad
    const bar = p1 ** p2 - 5 % p4;// bad
    // one may be confused into thinking (p1 || p2) && p3
    if (p1 || p2 && p3) {return p4;
    }// good
    const foo = (p1 && p2 < 0) || p3 > 0 || (p4 + 1 === 0);// good
    const bar = (p1 ** p2) - (5 % p4);// good
    if (p1 || (p2 && p3)) {return p4;
    }// good
    const bar = p1 + (p2 / p3 * p4);

? 返回目錄

代碼塊 Blocks

  • 13.3 如果 if 代碼塊中肯定會執行 return 語句,那么后面的 else 就沒必要寫了。如果在 else if 代碼塊中又有 if,并且 if 代碼塊會執行return 語句,那么可以分拆成多個 if 代碼塊。 eslint: no-else-return

    // bad
    const foo = function () {if (correct) {return correct;} else {return wrong;}
    };// bad
    const cats = function () {if (correct) {return correct;} else if (wrong) {return wrong;}
    };// bad
    const dogs = function () {if (correct) {return correct;} else {if (wrong) {return wrong;}}
    };// good
    const foo = function () {if (correct) {return correct;}return wrong;
    };// good
    const cats = function () {if (correct) {return correct;}if (wrong) {return wrong;}return false;
    };//good
    const dogs = function (correct) {if (correct) {if (confuse) {return wrong;}} else {return confuse;}
    };

? 返回目錄

注釋 Comments

? 返回目錄

空格 Whitespace

  • 15.8 不要在 block 代碼塊中加空行。 eslint: padded-blocks

    // bad
    const bar = function () {console.log(foo);};// bad
    if (baz) {console.log(qux);
    } else {console.log(foo);}// bad
    class Foo {constructor(bar) {this.bar = bar;}
    }// good
    const bar = function () {console.log(foo);
    };// good
    if (baz) {console.log(qux);
    } else {console.log(foo);
    }

  • 15.9 不要在小括號中加空格。 eslint: space-in-parens

    // bad
    const bar = function ( foo ) {return foo;
    };// good
    const bar = function (foo) {return foo;
    };// bad
    if ( foo ) {console.log(foo);
    }// good
    if (foo) {console.log(foo);
    }

  • 15.10 不要在中括號中加空格。 eslint: array-bracket-spacing

    // bad
    const foo = [ 1, 2, 3 ];
    console.log(foo[ 0 ]);// good
    const foo = [1, 2, 3];
    console.log(foo[0]);

  • 15.11 不要在大括號中加空格。 eslint: object-curly-spacing

    // bad
    const foo = { clark: 'kent' };// good
    const foo = {clark: 'kent'};

  • 15.12 盡量控制一行代碼在==100==個字符以內(包括空格)。字符串、字符串模板和 URL 不受限制。eslint: max-len

    為什么?這么做保證了可讀性和可維護性。

    // bad
    const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;// bad
    $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));// good
    const foo = jsonData&& jsonData.foo&& jsonData.foo.bar&& jsonData.foo.bar.baz&& jsonData.foo.bar.baz.quux&& jsonData.foo.bar.baz.quux.xyzzy;// good
    $.ajax({method: 'POST',url: 'https://airbnb.com/',data: {name: 'John',},
    }).done(() => {// do something...}).fail(() => {// do something...});

? 返回目錄

逗號 Commas

? 返回目錄

分號 Semicolons

? 返回目錄

類型轉換

? 返回目錄

命名規則

? 返回目錄

轉載于:https://www.cnblogs.com/huyuzhu/p/9138790.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/251638.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/251638.shtml
英文地址,請注明出處:http://en.pswp.cn/news/251638.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

筆試小結---樹

平衡二叉樹(Balanced Binary Tree):又被稱為AVL樹,且具有以下性質:它是一棵空樹或它的左右兩個子樹的高度差的絕對值不超過1&#xff0c;并且左右兩個子樹都是一棵平衡二叉樹。 二叉搜索樹&#xff1a;是一顆二叉樹&#xff0c;可能為空;若非空,則滿足以下特征: 1.每個元素有一…

iOS 快速實現分頁界面的搭建

級別&#xff1a; ★★☆☆☆ 標簽&#xff1a;「iOS」「分頁」「QiPageMenuView」 作者&#xff1a; 沐靈洛 審校&#xff1a; QiShare團隊 iOS 快速實現分頁界面的搭建 項目中我們經常會遇到滾動分頁的設計效果&#xff0c;被用來對不同數據界面的展示進行分類。我們先可以來…

java中String的常用方法

java中String的常用方法 轉自&#xff1a;http://archer-zhou.iteye.com/blog/443864 java中String的常用方法1、length() 字符串的長度例&#xff1a;char chars[]{a,b.c};String snew String(chars);int lens.length();2、charAt() 截取一個字符例&#xff1a;char ch;ch&quo…

筆試小結---非對稱加密算法

非對稱加密算法需要兩個密鑰:公開密鑰(publickey)和私有密鑰(privatekey).公開密鑰和私有密鑰是一對,如果公開密鑰對數據進行加密,只有用對應的私有密鑰才能解密;如果用私有密鑰進行加密,那么只有用對應的公開密鑰才能解密. 非對稱加密算法的保密性比較好,它消除了最終用戶交換…

登錄令牌 Token 介紹

Token值介紹 token 值: 登錄令牌.利用 token 值來判斷用戶的登錄狀態.類似于 MD5 加密之后的長字符串. 用戶登錄成功之后,在后端(服務器端)會根據用戶信息生成一個唯一的值.這個值就是 token 值. 基本使用: 在服務器端(數據庫)會保存這個 token 值,以后利用這個 token 值來檢索…

java-number

通常&#xff0c;當我使用number類型的時候&#xff0c;我們可以使用原始數據類型例如byte&#xff0c;int,long,double等 int i 5000; float b 13.65; double m 0xaf; 所有包裝類&#xff08;整型&#xff0c;長型&#xff0c;字節型&#xff0c;雙精度型&#xff0c;浮點型&a…

您的瀏覽器沒有獲得Java Virtual Machine(JVM)支持。可能由于沒有安裝JVM或者已安裝但是沒有啟用。請安裝JVM1.5或者以上版本,如果已安裝則啟用它。...

您的瀏覽器沒有獲得Java Virtual Machine(JVM)支持。可能由于沒有安裝JVM或者已安裝但是沒有啟用。請安裝JVM1.5或者以上版本&#xff0c;如果已安裝則啟用它。 https://www.java.com/zh_CN/download/faq/remove_olderversions.xml https://jingyan.baidu.com/article/6d704a13…

指令定義

restict&#xff1a;它告訴AngularJS這個指令在DOM中可以以何種形式被聲明。 E(元素&#xff09; <my-directive> </mydirective>A(屬性) <div my-directive“expression”> </div>C(類名) <div class“my-directive:expression;”> </div>…

MyBatis學習總結(9)——使用MyBatis Generator自動創建代碼

2019獨角獸企業重金招聘Python工程師標準>>> 由于MyBatis屬于一種半自動的ORM框架&#xff0c;所以主要的工作就是配置Mapping映射文件&#xff0c;但是由于手寫映射文件很容易出錯&#xff0c;所以可利用MyBatis生成器自動生成實體類、DAO接口和Mapping映射文件。這…

[BZOJ2125]最短路(圓方樹DP)

題意&#xff1a;仙人掌圖最短路。 算法&#xff1a;圓方樹DP&#xff0c;$O(n\log nQ\log n)$ 首先建出仙人掌圓方樹&#xff08;與點雙圓方樹的區別在于直接連割邊&#xff0c;也就是存在圓圓邊&#xff09;&#xff0c;然后考慮點u-v的最短路徑&#xff0c;顯然就是&#xf…

20162317 2017-2018-1 《程序設計與數據結構》第8周學習總結

20162317 2017-2018-1 《程序設計與數據結構》第8周學習總結 教材學習內容總結 1、二叉查找樹的定義、性質2、向二叉查找樹中添加元素的方法3、在二叉查找樹中刪除元素的方法4、旋轉的定義、方法、意義 教材學習中的問題和解決過程問題1&#xff1a;我在17章中看到這么一句話&a…

ES6模塊的轉碼

瀏覽器目前還不支持ES6模塊,為了實現立刻使用,我們可以將其轉為ES5的寫法.除了Babel可以用來轉碼,還有以下兩個方法也可以用來轉碼: ES6 moudule transpilerSystemJS ES6 moudule transpiler是square公司開源的一個轉碼器,可以將ES6模塊轉為CommonJS模塊或AMD模塊,從而在瀏覽器…

Java基礎學習總結(22)——異常處理

2019獨角獸企業重金招聘Python工程師標準>>> 一、異常的概念 異常指的是運行期出現的錯誤&#xff0c;也就是當程序開始執行以后執行期出現的錯誤。出現錯誤時觀察錯誤的名字和行號最為重要。 1 package cn.javastudy.summary;2 3 public class TestEx{4 5 …

XAML中格式化日期

要求被格式化數據的類型是DateTime StringFormatyyyy-MM-dd StringFormat{}{0:yyyy-MM-dd}轉載于:https://www.cnblogs.com/changbaishan/p/9144584.html

130242014045 林承暉 第2次實驗

軟件體系結構的第二次實驗&#xff08;解釋器風格與管道過濾器風格&#xff09; 一、實驗目的 1&#xff0e;熟悉體系結構的風格的概念 2&#xff0e;理解和應用管道過濾器型的風格。 3、理解解釋器的原理 4、理解編譯器模型 二、實驗環境 硬件&#xff1a; 軟件&#xff1a;P…

AnularJS1事件

在Web應用的組件是松耦合的情況下&#xff0c;比如需要用戶驗證然后處理授權&#xff0c;即時的通信不總是可行的&#xff0c;因為組件沒有耦合在一起。 例如&#xff0c;如果后端對一個請求返回了狀態碼401&#xff08;表明一個未經授權的請求&#xff09;&#xff0c;我們期望…

Java基礎學習總結(8)——super關鍵字

2019獨角獸企業重金招聘Python工程師標準>>> 一、super關鍵字 在JAVA類中使用super來引用父類的成分&#xff0c;用this來引用當前對象&#xff0c;如果一個類從另外一個類繼承&#xff0c;我們new這個子類的實例對象的時候&#xff0c;這個子類對象里面會有一個父類…

conda鏡像

轉自https://blog.csdn.net/guilutian0541/article/details/81004769 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main conda config --set show…

Java基礎學習總結(17)——線程

2019獨角獸企業重金招聘Python工程師標準>>> 一、線程的基本概念 線程理解&#xff1a;線程是一個程序里面不同的執行路徑 每一個分支都叫做一個線程&#xff0c;main()叫做主分支&#xff0c;也叫主線程。 程只是一個靜態的概念&#xff0c;機器上的一個.class文件…

(轉)MySQL自帶的性能壓力測試工具mysqlslap詳解

mysqlslap 是 Mysql 自帶的壓力測試工具&#xff0c;可以模擬出大量客戶端同時操作數據庫的情況&#xff0c;通過結果信息來了解數據庫的性能狀況 mysqlslap 的一個主要工作場景就是對數據庫服務器做基準測試 例如我們拿到了一臺服務器&#xff0c;準備做為數據庫服務器&#x…