// bad if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") { //logic } // better if (["abc", "def", "ghi", "jkl"].includes(x)) { //logic }
2. 简化 iftrue…else 条件表达式
// bad lettest: boolean; if (x > 100) { test = true; } else { test = false; } // better let test = x > 10 ? true : false; //or let test = x > 10; console.log(test);
3. 假值(undefined,null,0,false,NaN,emptystring)检查
当我们创建⼀个新变量时,有时我们想检查引⽤的变量是否是⼀个假值,例如 null 或 undefined 或空字符串。JavaScript 确实为这种检查提供了⼀个很好的快捷⽅式⸺逻辑 OR 运算符(||) || 仅当左侧为空或 NaN 或 null 或 undefined 或 false 时,如果左侧操作数为假,则将返回右侧操作数,逻辑或运算符(||)将返回右侧的值。
// bad if (test1 !== null || test1 !== undefined || test1 !== "") { let test2 = test1; } // better let test2 = test1 || ""; // bad if (test1 === true) or if (test1 !== "") or if (test1 !== null) // better if (test1){ // do some }else{ // do other }
4. null/undefined 检查和默认赋值
//null checking and default assignment let test1 = null; let test2 = test1 ?? ""; console.log("null check", test2); // output empty string "" //undefined checking and default assignment const test = undefined ?? "default"; console.log(test); // expected output: "default"
switch (data) { case1: test1(); break; case2: test2(); break; case3: test(); break; // And so on... } // better var data = { 1: test1, 2: test2, 3: test, }; // If type exists in data, execute the corresponding function data[type] && data[type]();
// bad const data = "hello maxwell this is a test\n\t" + "test test,test test test test\n\t"; // better const data = `hello maxwell this is a test test test,test test test test`;
16. indexOf 的按位化简
在数组中查找某个值时,我们可以使⽤ indexOf()⽅法。但是还有更好的⽅法,我们来看这个例⼦。
// bad if (arr.indexOf(item) > -1) { // item found } if (arr.indexOf(item) === -1) { // item not found } // better if (~arr.indexOf(item)) { // item found } if (!~arr.indexOf(item)) { // item not found } //The bitwise (~) operator will return true (except for -1), //the reverse operation only requires !~. Alternatively, the includes() function can be used. if (arr.includes(item)) { // true if the item found }
// bad let total = parseInt("583"); let average = parseFloat("32.5"); // better let total = +"583"; let average = +"32.5";
18. 按顺序执⾏ Promise
如果你有⼀堆异步或普通函数都返回要求你⼀个⼀个执⾏它们的 Promise 怎么办?
asyncfunctiongetData() { const promises = [fetch("url1"), fetch("url2"), fetch("url3"), fetch("url4")]; for (const item of promises) { // Print out the promise console.log(item); } // better forawait (const item of promises) { // Print out the results of the request console.log(item); } }