18个编写JavaScript代码的技巧

1、对常量使用“ const”而不是“ var”
/* Wrong */var i = 1;/* Correct */const i = 1;
2、对更改的变量使用“ let”代替“ var”
/* Wrong */var myVal = 1;for (var i; i < 10; i++){myVal = 1 + i;}/* Correct */let myVal = 1;for (let i; i < 10; i++){myVal += i}
3、声明对象
/* Wrong */const myObject = new Object();/* Correct */const myObject = {};
4、声明数组
/* Wrong */const myArray = new Array();/* Correct */const myArray = [];
5、连接字符串
/* Wrong */const myStringToAdd = "world";const myString = "hello " + myStringToAdd;/* Correct */const myStringToAdd = "world";const myString = `hello ${myStringToAdd}`;
6、使用对象方法的简写
/* Wrong */const customObject = {val: 1,addVal: function () {return customObject.val + 1;}}/* Correct */const customObject = {val: 1,addVal(){return customObject.val++}}
7、创建对象的值
/* Wrong */const value = 1;const myObject = {value: value}/* Correct */const value = 1;const myObject = {value}
8、为对象分配值
/* Wrong */const object1 = { val: 1, b: 2 };let object2 = { d: 3, z: 4 };object2.val = object1.val;object2.b = object1.b;/* Correct */const object1 = { val: 1, b: 2 };const object2 = { ...object1, d: 3, z: 4 }
9、给数组赋值
/* Wrong */const myArray = [];myArray[myArray.length] = "hello world";/* Correct */const myArray = [];myArray.push('Hello world');
10、串联数组
/* Wrong */const array1 = [1,2,3,4];const array2 = [5,6,7,8];const array3 = array1.concat(array2);/* Correct */const array1 = [1,2,3,4];const array2 = [5,6,7,8];const array3 = [...array1, ...array2]
11、获取对象的多个属性
/* Wrong */function getFullName(client){return `${client.name} ${client.last_name}`;}/* Correct */function getFullName({name, last_name}){return `${name} ${last_name}`;}
12、从对象获取值
/* Wrong */const object1 = { a: 1 , b: 2 };const a = object1.a;const b = object1.b;/* Correct */const object1 = { a: 1 , b: 2 };const { a, b } = object1;
13、创建功能
/* Wrong */function myFunc() {}/* Wrong */const myFunc = function() {}/* Correct */const myFunct = () => {}
14、默认值
/* Wrong */const myFunct = (a, b) => {if (!a) a = 1;if (!b) b = 1;return { a, b };}/* Correct */const myFunct = (a = 1, b = 1) => {return { a, b };}
15、用“ reduce”代替“ forEach”和“ for”来求和
/* Wrong */const values = [1, 2, 3, 4, 5];let total = 0;values.forEach( (n) => { total += n})/* Wrong */const values = [1, 2, 3, 4, 5];let total = 0;for (let i; i < values.length; i++){total += values[i];}/* Correct */const values = [1, 2, 3, 4, 5];const total = values.reduce((total, num) => total + num);
16、存在于数组中
/* Wrong */const myArray = [{a: 1}, {a: 2}, {a: 3}];let exist = false;myArray.forEach( item => {if (item.a === 2) exist = true})/* Correct */const myArray = [{a: 1}, {a: 2}, {a: 3}];const exist = myArray.some( item => item.a == 2)
17、布尔值的快捷方式
/* Wrong */const a = 1;const b = 1;let isTrue = falseif (a === b) {isTrue = true}/* Correct */const a = 1;const b = 1;const isTrue = a === b
18、值的快捷方式
/* Wrong */const a = 5;let b;if (a === 5){b = 3;} else {b = 2;}/* Correct */const a = 5;const b = a === 5 ? 3 : 2;
结论

评论
