How to write readable, practical and high-quality JavaScript code, you need to have some tips

Although writing code as before, now have eslint, prettier, babel (write the new syntax) to ensure these code format, however, another high-end technology can not solve the readability of the code (the code can be the future of themselves and their colleagues read) problem, because the problem only themselves to resolve. To let you write your colleague or transfer Tucao code, the code must first have a good style, following the encoding bad habits you have wood there? Any improvement to get rid of it! ! !
JavaScript have some beneficial tips to improve your code quality Oh! Let's work together to learn it! !
1. Variable abuse
after a good definition never used
to improve:
the data is not used or used only once there is no need to install variable, useless, delete it, or delete three months themselves are afraid, fear is not it uses
2 feel-good acronym

let fName = 'jack'; // 看起来命名挺规范,缩写,驼峰法都用上,ESlint 各种检测规范的工具都通过,
//But,fName 是啥?这时候,你是不是想说 What are you 弄啥呢?
let lName = 'tom'; // 这个问题和上面的一样

Improve:

let firstName = 'jack'; // 怎么样,是不是一目了然。少被喷了一次
let lastName = 'tom';//无需对每个变量都写注释,从名字上就看懂

3. Parameter None Description of

if (value.length < 8) { // 为什么要小于 8,8 表示啥?长度,还是位移,还是高度?Oh,my God!!
    ....
}

Improve:

const MAX_INPUT_LENGTH = 8;//添加变量
if (value.length < MAX_INPUT_LENGTH) { // 一目了然,不能超过最大输入长度
    ....
}

4. Name is too long-winded

let nameString;
let theUsers;

Improved:
clear and concise on the line

let name;
let users;

5. Too many global variables

name.js
window.name = 'tom';
hello.js
window.name = 'bobu';
time.js
window.name = 'cater';  // 三个文件的先后加载顺序不同,都会使得 window.name 的值不同,
//同时,你对 window.name 的修改了都有可能不生效,因为你不知道你修改过之后别人是不是又在别的说明文件中对其的值重置了。
//所以随着文件的增多,会导致一团乱麻。

Improvement:
less or alternatives: you can choose to use only local variables. Method () {} a.
If you do use a lot of global variables need to share, you can use vuex, redux or your own reference flux model also write a line.

6. From the name can not know the function return value type

function showDatas() {....} // 现在问,你知道这个返回的是一个数组,还是一个对象,还是 true or false

Improvement:
For the function returns true or false, preferably in should / is / can / beginning has

function shouldShowData() {...}
function isEmpty() {...}
function canSubmit() {...}
function hasLicense() {...}

7. Output function changeable function

function plusAbc(a, b, c) {  // 这个函数的输出将变化无常,因为 api 返回的值一旦改变,同样输入函数的 a,b,c 的值,但函数返回的结果却不一定相同。
        var c = fetch('../api');
        return a+b+c;
}

Improved:
performance function using pure function, consistent input, the output is always unique

function plusAbc(a, b, c) {  // 同样输入函数的 a,b,c 的值,但函数返回的结果永远相同。
        return a+b+c;
}

8. No description parameter passing

getLisence(src, true, false); // true 和 false 啥意思,一目不了然

Improved:
parameter passing a note

getLisence({
    image: src,
    includePageBackground: true, // 一目了然,知道这些 true 和 false 是啥意思
    compress: false,
})

9. unable to discern the intent function
improvement:
the beginning of the verb, the intention is quite clear function

function sendEmailr(user) {
    ....
}

10. The use of excessive function if else

function getGrades(num){
	let result='';//返回结果
	if(num < 60) {
		result = "不及格";
	}else if(num < 75) {
		result = "一般";
	} else if(num < 90){
		result = "良好";
	}else{
		result = "优秀";
	}
	return result;
}
console.log(getGrades(60))

Improvement:
1 may be usedswitch Or use alternativeArraySubstitute

function showGrace(grades,results,curr) {
	for(let i in grades){
		if(curr<grades[i]){
			return results[i]
		}
	}
}
let grades=[60,75,90,101],
results=['不及格','一般','良好','优秀'];
showGrace(grades,results,60)

2. The short-circuit evaluation (Short-Circuit Evaluation): ternary operator is a very convenient to write some simple logic statements embodiment,
X> 100 'Above 100': 'Below 100';?
X> 100 (? X> 200 is 'Above 200 is': 'the Between 100-200'):? 'Below 100';
11.if determination condition too

if(fruit==='apple' || fruit==='apple' || fruit==='strawberry' || fruit==='cherry' || fruit==='cranberries'){
	console.log('red');
}else{
	console.log('blue');
}

Improvement:
using an array of conditions include,
The Array.indexOf the method determines whether there is a value in the array, return the array elements if the presence of the subscript, otherwise -1;
array.find (the callback [, thisArg]) Returns the array satisfy the condition value of the first element, if not, returns undefined;
array.findIndex (the callback [, thisArg]) returns the index of the first element in the array satisfies the conditions (subscript), if not found, return -1
array. includes (searchElement [, fromIndex]) this method determines whether there is a value in the array, returns true if present, otherwise returns false.

function test(fruit) {
	const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
	if (redFruits.includes(fruit)) {
		console.log('red');
	}else{
		console.log('blue');
	}
}

12. The return data validity determination

if (this.state.data) {
  return this.state.data;
} else {
  return 'Fetching Data';
}
但是我们可以通过上面的方式来简写这个逻辑处理。

return (this.state.data || 'Fetching Data');

13. Try to use for ES6
1. try to use the function arrow
2. + without using the traditional number of template characters using

// var message = 'Hello ' + name + ', it\'s ' + time + ' now'
改进:var message = `Hello ${name}, it's ${time} now`

3. Use the deconstruction assignment
traditional assignment:

var data = { name: 'dys', age: 1 };
var name = data.name;
var age = data.age;
var fullName = ['jackie', 'willen'];
var firstName = fullName[0];
var lastName = fullName[1];

Improved:
Deconstruction assignment:

const data = {name:'dys', age:1};
const {name, age} = data;   // 怎么样,是不是简单明了
var fullName = ['jackie', 'willen'];
const [firstName, lastName] = fullName;

4. make use of class-based
traditional function prototype inheritance chain
typically ES5 class (function) in succession poor readability, construction and method definitions, inheritance when necessary, and a preferred class. Code too, is omitted.
Improvement:
using ES6 class inheritance

class Animal {
  constructor(age) {
    this.age = age
  }
  move() {
    /* ... */
  }
}
class Mammal extends Animal {
  constructor(age, furColor) {
    super(age)
    this.furColor = furColor
  }
  liveBirth() {
    /* ... */
  }
}
class Human extends Mammal {
  constructor(age, furColor, languageSpoken) {
    super(age, furColor)
    this.languageSpoken = languageSpoken
  }
  speak() {
    /* ... */
  }
}

5. Filter unique value
Set new type of in ES6, which is similar to the array, but the value of the member are unique, there is no duplicate values. Combined with the expansion operator (...) we can create a new array, the original array to achieve filtering duplicate values.
Array = const [. 1, 2,. 3,. 3,. 5,. 5,. 1];
const uniqueArray = [... the Set new new (Array)];
the console.log (uniqueArray); // [. 1, 2,. 3,. 5]
in before ES6, if we want to achieve this function, then the processing code needs to be a lot more. The scope of application of the technique is the type of value in the array is: undefined, null, boolean, string , number. When the inclusion object, function, array, there are no applicable.

PS: Tips
1, converts the Boolean
conventional type boolean value only true and false, but we can be in JavaScript other values considered to be 'truthy' or 'falsy' of.
In addition to 0, "", null, undefined , NaN and false, others we can be considered 'truthy' of.
We can minus operator! Converting the variable into a series of "boolean" type.

const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;
console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"

2, converts a String
we can connect + operator to a variable of type number is converted into a string type.

const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

3, Number type conversion
and corresponding to the above, we can by the addition operator + is a variable of type string back to number type.

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

In some contexts, + to be interpreted as concatenation operator, rather than the addition operator. When this happens (you want to return an integer rather than floating), you can use two tilde: ~ ~.
(Note that in English format)

A tilde ~, known as the "bit is not operator", equivalent to - n - 1. Therefore, ~ 15 = -16.
Two ~ effectively negate operation. This is because - (- n - 1) - 1 = n + 1 - 1 = n. That to -16 = 15

const int = ~~"15"
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

4, fast exponentiation
from the beginning ES7, we can use the exponentiation operator ** exponentiation as shorthand, Math.pow (2, 3) before relatively faster. This is a very simple and practical point, but most of it devoted to the tutorial does not.

console.log (2 ** 3); // Result: 8
This should not be confused with the caret, the caret typically used to represent the index, but in JavaScript is bit XOR operator.
Before ES7, power shorthand relies mainly on bit left shift operator <<, the difference between the wording of several.

// 下面几种写法是等价的
Math.pow(2, n);
2 << (n - 1);
2**n;
其中需要注意的是 2 << 3 = 16 等价于 2 ** 4 = 16

5, Fast Integer Float switch
We usually use Math.floor (), Math.ceil () and Math.round () to convert the integer to a float type.
But there is a faster method can be used | (bitwise OR operator) will float truncated to an integer.

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23

| The behavior depends on the processing is positive or negative, so it is best to use only the shortcut in the case determined.
If n is a positive number, the n | 0 effectively rounded down. If n is negative, it is rounded up effectively. More precisely, the operating result is the contents of the delete decimal point, floating point numbers truncated to an integer, and several other methods mentioned above is somewhat different.
You can also use ~ to get the same effect of rounding, as described above, virtually any site operators will be forced to float to an integer. These special operation is efficient because once forced to integer value remains unchanged.
Be used:
bit or operator can be used to remove any number of integer numbers from the end. This means that we do not have to use such a code to switch between types.

let str = "1553"; 
Number(str.substring(0, str.length - 1));
而是可以使用下面的方式来实现我们的功能
console.log(1553 / 10   | 0)  // Result: 155
console.log(1553 / 100  | 0)  // Result: 15
console.log(1553 / 1000 | 0)  // Result: 1

6, automatic binding class

We can use the arrow ES6 increase function in a class way to achieve stealth binding scope. And in accordance with the previous process, we need to explicitly bind to the way we write, similar to this.myMethod = this.myMethod.bind (this) case. When our class there are many ways to write code that will increase the large number of binding. Now we can simplify this process by way of the arrow function.

import React, { Component } from React;
export default class App extends Compononent {
  constructor(props) {
    super(props);
    this.state = {};
  }
  myMethod = () => {
    // 隐式绑定
  }
  render() {
    return (
      <>
        <div>
          {this.myMethod()}
        </div>
      </>
    )
  }
};

7, the interception of an array
if you want to delete from the end of the array of values, than there splice () faster alternative.
For example, if you know the length of the original array, can be achieved by redefining its intercept length property.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

This is a particularly elegant solution. However, faster running slice () method of the time. If speed is your primary goal, consider using the following method.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array); // Result: [0, 1, 2, 3]

8, retrieve the last element in the array of
arrays method slice () can accept negative integer, if it is provided, it will start from the end of the interception value of the array, rather than the beginning.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

9, JSON formatting code that
we could handle relevant in dealing with some JSON very often use to JSON.stringify, but whether you realize it can help indent JSON it?
the stringify () method takes two optional parameters: a replacer function value and a space, JSON replacer function can be used to filter displayed.
space accepts an integer value representing the number of spaces required or a string (e.g., '\ t' to insert a tab), which can read data acquired JSON much easier.

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

Guess you like

Origin blog.csdn.net/qq_36711388/article/details/89792482