乐趣区

关于javascript:JavaScript最佳实践数据

1. Foundational practice: Always use strict mode

“use strict”;

应用严格模式,能够使得浏览器运行 js 代码更加标准。例如

`"use strict";
city = "shenzhen";
console.log(city);` 

在严格模式下运行,浏览器会查看出谬误。Uncaught ReferenceError: city is not defined

`"use strict";
module.exports = {
    env:{es6:true},
    rules:{"strict":["error","global"]
    }
};` 

2.Declaring Variables

Prefer const, then let.    优先应用 const 再是 let,不应用 var

规定:no-var

绝对 var,let 申明的对象作用域不会泄露。变量名不能屡次申明,例如:

`let type = "testType";
// 再次申明
let type = "testAgain";` 

规定:no-redeclare ,  prefer-const

应用 const 能够避免变量被意外批改。

Use individual states to create variables;      一个申明创立一个变量

最佳实际表明,这样有利于代码调试且不便浏览代码。

`"use strict";
let color,
  background,
  size;
const rate = 65.9,
  markup = 0.1;
// 比照代码 ====================================
let color;
let background;
let size;
const rate = 65.9;
const markup = 0.1;` 

规定:one-var

Create descriptive variable names      创立具备形容意义的变量名

`//snake Case 
let sz_inventory_ratio = 0.2;
//camel Case
let szInventoryRatio = 0.2;` 

    应用驼峰命名规定,规定:camelcase

Standardize acronym case       标准化字母缩写体

`const cogs = 12.7;                    //COGS: cost of goods sold
const YtdSales = 15.3;                //YTD: year to date
const NOP = YtdSales - cogs;           //NOP: net operating profit
//=========== 批改后 ===========
const COGS = 12.7;
const YTDSales = 15.3;
const NOP = YTDSales - COGS;` 

Remove unused variables      去除没有应用的变量

规定:no-unused-vars

参考 .eslintrc.js

`"use strict";
module.exports = {
    env:{es6:true},
    rules:{"strict":["error","global"],
        "no-var":"error",
        "prefer-const":"error",
        "one-var": ["error", "never"],
        "camelcase": "error",
        "no-unused-vars": "error"
    }
};` 

3.Assigning Values

Don’t assign variables in chains      不容许链式赋值

`let subTotal;
let shipping;
let netTotal;
subTotal = shipping = netTotal = 0;    // 链式赋值

//===== 批改后 ======
subTotal = 0;
shipping = 0;
netTotal = 0;` 

规定:no-multi-assign

Standardize qutoes      标准化引号

     js 定义字符串对象,默认对双引号 ”, 单引号‘都反对。Es6 反对 backtick `。然而在我的项目要求对立。json 文件只反对双引号。要求我的项目中默认对立应用双引号

规定:quotes

Create arrays and objects using Literals      应用文本创立数组和对象,不容许应用构造函数

new Array()初始化数组令人困惑

因而,为了失去统一的后果,也为了代码简洁。要求初始化数组和对象对立应用文本。例如:

let arr2 = [2];

let arr3 = [2,3,2];

规定:no-array-constructor , no-new-object

Quote object property names consistently      对象属性名应用引号

定义对象,其属性名,也就是 key,如果两头有特殊字符 (-,_) 就须要用双引号突围。

`const sessions = {
  plenary: "The latest buzz in beekeeping",
  "morning-beginner": "Hive management 101",
  "morning-expert": "Advances in mite control"
};` 

通常定义属性名要求驼峰命名,这样束缚能够不便查看哪些属性没有这样命名。

规定:quote-props

参考 .eslintrc.js

`"use strict";

module.exports = {
  env: {es6: true,},
  rules: {strict: ["error", "global"],
    "no-var": "error",
    "prefer-const": "error",
    "one-var": ["error", "never"],
    "camelcase": "error",
    "no-unused-vars": "error",
    "no-multi-assign": "error",
    "quotes": ["error", "single"],
    "no-array-constructor": "error",
    "no-new-object": "error",
    "quote-props": ["error","as-needed"]
  }
};` 

4.Type Casting

Type cast strings with the String wrapper    应用 String()转换字符串类型

字符串类型转换,应用 new String(el), el.toString(), 会有歧义。参考如下:

``"use strict";

const formData = [55];

formData.forEach((el) => {console.log(`n${el}:`);
  console.table({"new String()": {result: `${new String(el)}`, 
      "data type": `${typeof new String(el)}`,
    },
    toString: {result: `${el.toString()}`, 
      "data type": `${typeof el.toString()}`,
    },
    "String()": {result: `${String(el)}`, 
      "data type": `${typeof String(el)}`,
    },
  });
});`` 

字符类型转换比照后果

如果变量是 undefined, 应用 toString 办法会抛错。

因而字符串变量转换最好的形式就是应用 String(). 规定:no-new-wrappers

Type cast numbers with the Number wrapper      应用 Number()转换数字类型

应用 new Number()转换数字类型有歧义,参考如下:

``"use strict";

const formData = ["55", true, undefined];

formData.forEach((el) => {console.log(`n${el}:`);
  console.table({"new Number()": {result: `${new Number(el)}`, 
      "data type": `${typeof new Number(el)}`,
    },
    "Number()": {result: `${Number(el)}`, 
      "data type": `${typeof Number(el)}`,
    },
  });
});`` 

运行后果:

55:

true:

undefined:

规定同上:no-new-wrappers

Type cast Booleans using double negation      应用两次非运算 !! 转换布尔类型

应用 new Boolean()转换布尔类型有歧义,参考如下:

``"use strict";

const formData = ["flower", 0, undefined];

formData.forEach((el) => {console.log(`n${el}:`);
  console.table({"new Boolean()": {result: `${new Boolean(el)}`, 
      "data type": `${typeof new Boolean(el)}`,
    },
    "Boolean()": {result: `${Boolean(el)}`, 
      "data type": `${typeof Boolean(el)}`,
    },
    "!!": {result: `${!!el}`, 
      "data type": `${typeof !!el}`,
    }  
  });
});`` 

运行后果:

flower:

0:

underfined:

应用 Boolean(), !! 都能失去正确的数据类型,然而为了代码简洁,通常应用!!

规定同上:no-new-wrappers

Rely on implicit Boolean values in conditionsals      在条件中应用隐式布尔类型

`let logged = true;
if(!!logged){        // 多余的转换
    //do something...
}
if(logged === true){        // 多余的判断
    //do something...
}
// 正确的姿态
if(logged){//do something...}` 

规定: no-extra-boolean-cast

5.Comparing Values

Use triple-character equality operators      应用 === 作为相等操作符

js 有两个比拟符号 “==”, “===”,双等号做比拟判断会有歧义,参考代码:

``"use strict";

const data = [0, "", false, null];

data.forEach((el) => {if (el == "0") {console.log(`${el} == "0"`);
  } 
  if (el == undefined) {console.log(`${el} == undefined`);
  } 
});`` 

运行后果:

0 == “0”

false == “0”

null == undefined

更为具体的比照参考:https://dorey.github.io/JavaS…

规定: eqeqeq

Don’t use Yoda conditions      不应用 Yoda 条件判断

Yoda 特指条件比拟时,先列出条件再写出变量的这种倒装式的写法:

`if ("1" === data.alert) {    //Yoda
  //...    
} 
if (3 < value){    //Yoda
    //...
}
// 正确的写法
if (data.alert === "1"){//...}
if (value > 3){//...}` 

规定:yoda

Compare appropriately for the data type      数据类型失当的比拟

``"use strict";

const data = {
  warning: true,
  warningText: "Solar flare may disrupt communications",
  notes: "",
  alert: 2,
  obj: {o1: "hello", o2: 222}
};

if (data.warning) {console.log(data.warningText);
}
if (data.notes) {console.log(data.notes);
}
if (data.alert) {if (data.alert === 1) {console.log("Winter storm");
  } else if (data.alert === 2) {console.log("High wind");
  } else if (data.alert === 3) {console.log("Hurricane");
  } else if (data.alert === 4) {console.log("Heat advisory");
  }  
}
if(data.obj){console.log(`data.obj.o1=${data.obj.o1}`)
}
//============ 举荐写法 ==========
if (data.warning) {console.log(data.warningText);
}
if (data.notes !== "") {console.log(data.notes);
}
if (data.alert > 0) {if (data.alert === 1) {console.log("Winter storm");
  } else if (data.alert === 2) {console.log("High wind");
  } else if (data.alert === 3) {console.log("Hurricane");
  } else if (data.alert === 4) {console.log("Heat advisory");
  }  
}
if(!!data.obj){console.log(`data.obj.o1=${data.obj.o1}`)
}`` 

Use ternary statements judiciously      理智的应用三目比拟符

``"use strict";

const data = {
  warning: true,
  warningText: "Solar flare may disrupt communications",
};
const warning = data.warning ? true : false;

console.log(`Warning: ${(warning) ? data.warningText : "No warning message at this time"}`);

//========== 洁净的写法 =============
const nullWarning = 'No warning message at this time';
const warning = data.warning;
const text = data.warningText;

console.log(`Warning: ${(warning) ? text : nullWarning}`);`` 

Add parentheses to clarify logic      加 () 使逻辑清晰

while (thirdChoice === firstChoice || thirdChoice === secondChoice) {thirdChoice = choose();
}
// 清晰的写法
while ((thirdChoice === firstChoice) ||
       (thirdChoice === secondChoice)) {thirdChoice = choose();
}

原文链接 https://www.sdk.cn/details/emdvzb3PQRem8jqQPA

SDK 社区是一个中立的社区,这里有多样的前端常识,有丰盛的 api,有爱学习的人工智能开发者,有有趣风趣的开发者带你学 python,还有将来炽热的鸿蒙,当各种元素组合在一起,让咱们一起脑洞大开独特打造业余、好玩、有价值的开发者社区,帮忙开发者实现自我价值!

退出移动版