1. 含有多个条件的 if 语句
我们可以在数组中存储多个值,并且可以使用数组的 includes 方法。
1//longhand 2if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') { 3 //logic 4} 5//shorthand 6if (['abc', 'def', 'ghi', 'jkl'].includes(x)) { 7 //logic 8}
2. If … else 的缩写法
当我们的 if-else 条件中的逻辑比较简单时,可以使用这种简洁的方式——三元条件运算符。
1// Longhand 2let test: boolean;if (x > 100) { 3 test = true; 4} else { 5 test = false; 6} 7// Shorthand 8let test = (x > 10) ? true : false; 9//or we can use directly 10let test = x > 10;console.log(test);
如果包含嵌套的条件,我们也可以这样写。
1let x = 300, 2test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';console.log(test2); // "greater than 100"
3. 定义变量
当我们定义两个值相同或类型相同的变量,可以使用这样的缩写法
1//Longhand 2let test1; 3let test2 = 1; 4//Shorthand 5let test1, test2 = 1; 6
4. 对 Null、Undefined、Empty 这些值的检查
我们创建一个新变量,有时候需要检查是否为 Null 或 Undefined。JavaScript 本身就有一种缩写法能实现这种功能。
1// Longhand 2if (test1 !== null || test1 !== undefined || test1 !== '') { 3 let test2 = test1; 4} 5// Shorthand 6let test2 = test1 || '';
5. 对 Null 值的检查以及默认赋值
1let test1 = null, 2 test2 = test1 || '';console.log("null check", test2); // output will be ""
6. 对 Undefined 值的检查以及默认赋值
1let test1 = undefined, 2 test2 = test1 || '';console.log("undefined check", test2); // output will be ""
对正常值的检查
1let test1 = 'test', 2 test2 = test1 || '';console.log(test2); // output: 'test'
利好消息:关于第 4、5、6 条还可以使用 ?? 运算符
聚合运算符
**??**是聚合运算符,如果左值为 null 或 undefined,就返回右值。默认返回左值。
1const test= null ?? 'default'; 2console.log(test); 3// expected output: "default"const test1 = 0 ?? 2; 4console.log(test1); 5// expected output: 0
7. 同时为多个变量赋值
当我们处理多个变量,并且需要对这些变量赋不同的值,这种缩写法很有用。
1//Longhand 2let test1, test2, test3; 3test1 = 1; 4test2 = 2; 5test3 = 3; 6//Shorthand 7let [test1, test2, test3] = [1, 2, 3];
8. 赋值运算符缩写法
编程中使用算术运算符是很常见的情况。以下是 JavaScript 中赋值运算符的应用。
1// Longhand 2test1 = test1 + 1; 3test2 = test2 - 1; 4test3 = test3 * 20; 5// Shorthand 6test1++; 7test2--; 8test3 *= 20;
9. 判断变量是否存在的缩写法
这是普遍使用的缩写法,但在这里应当提一下。
1// Longhand 2if (test1 === true) or if (test1 !== "") or if (test1 !== null) 3 4// Shorthand 5//it will check empty string,null and undefined too 6if (test1)
注意:当 test1 为任何值时,程序都会执行 if(test1){ } 内的逻辑,这种写法在判断 NULL 或 undefined 值时普遍使用。
10. 用于多个条件的与(&&)运算符
如果需要实现某个变量为 true 时调用一个函数,可以使用 && 运算符。
1//Longhand 2if (test1) { 3 callMethod(); 4} //Shorthand 5test1 && callMethod();
11. foreach 循环缩写法
这是循环结构对应的缩写法。
1// Longhand 2for (var i = 0; i < testData.length; i++) 3 4// Shorthand 5for (let i in testData) or for (let i of testData)
Array for each variable
1function testData(element, index, array) { 2 console.log('test[' + index + '] = ' + element); 3} 4 5[11, 24, 32].forEach(testData); 6// logs: test[0] = 11, test[1] = 24, test[2] = 32
12. 比较结果的返回
在 return 语句中,我们也可以使用比较的语句。这样,原来需要 5 行代码才能实现的功能,现在只需要 1 行,大大减少了代码量。
1// Longhand 2let test;function checkReturn() { 3 if (!(test === undefined)) { 4 return test; 5 } else { 6 return callMe('test'); 7 } 8} 9var data = checkReturn(); 10console.log(data); //output testfunction callMe(val) { 11 console.log(val); 12}// Shorthandfunction checkReturn() { 13 return test || callMe('test'); 14}
13. 箭头函数
1//Longhand 2function add(a, b) { 3 return a + b; 4} 5//Shorthand 6const add = (a, b) => a + b;
再举个例子
1function callMe(name) { 2 console.log('Hello', name); 3}callMe = name => console.log('Hello', name);
14. 简短的函数调用语句
我们可以使用三元运算符实现如下功能。
1// Longhand 2function test1() { 3 console.log('test1'); 4}; 5function test2() { 6 console.log('test2'); 7}; 8var test3 = 1; 9if (test3 == 1) { 10 test1(); 11} else { 12 test2(); 13} 14// Shorthand 15(test3 === 1? test1:test2)();
15. switch 对应的缩写法
我们可以把条件值保存在名值对中,基于这个条件使用名值对代替 switch。
1// Longhand 2switch (data) { 3 case 1: 4 test1(); 5 break; 6 7 case 2: 8 test2(); 9 break; 10 11 case 3: 12 test(); 13 break; 14 // And so on... 15} 16 17// Shorthand 18var data = { 19 1: test1, 20 2: test2, 21 3: test 22}; 23 24data[something] && data[something]();
16. 隐式返回缩写法
使用箭头函数,我们可以直接得到函数执行结果,不需要写 return 语句。
1//longhand 2function calculate(diameter) { 3 return Math.PI * diameter 4} 5//shorthand 6calculate = diameter => ( 7 Math.PI * diameter; 8)
17. 十进制数的指数形式
1// Longhand 2for (var i = 0; i < 10000; i++) { ... } 3 4// Shorthand 5for (var i = 0; i < 1e4; i++) {
18. 默认参数值
1//Longhand 2function add(test1, test2) { 3 if (test1 === undefined) 4 test1 = 1; 5 if (test2 === undefined) 6 test2 = 2; 7 return test1 + test2; 8} 9//shorthand 10add = (test1 = 1, test2 = 2) => (test1 + test2);add() //output: 3
19. 延展操作符的缩写法
1//longhand// joining arrays using concat 2const data = [1, 2, 3]; 3const test = [4 ,5 , 6].concat(data); 4//shorthand// joining arrays 5const data = [1, 2, 3]; 6const test = [4 ,5 , 6, ...data]; 7console.log(test); // [ 4, 5, 6, 1, 2, 3] 8
我们也可以使用延展操作符来克隆。
1//longhand 2 3// cloning arrays 4const test1 = [1, 2, 3]; 5const test2 = test1.slice() 6//shorthand 7 8// cloning arrays 9const test1 = [1, 2, 3]; 10const test2 = [...test1];
20. 文本模板
如果你对使用 + 符号来连接多个变量感到厌烦,这个缩写法可以帮到你。
1`//longhand 2const welcome = 'Hi ' + test1 + ' ' + test2 + '.' 3//shorthand 4const welcome = `Hi ${test1} ${test2}`;
21. 跟多行文本有关的缩写法
当我们在代码中处理多行文本时,可以使用这样的技巧
1`//longhand 2const data = 'abc abc abc abc abc abc\n\t' 3 + 'test test,test test test test\n\t' 4//shorthand 5const data = `abc abc abc abc abc abc 6 test test,test test test test`
22. 对象属性的赋值
1let test1 = 'a'; 2let test2 = 'b'; 3//Longhand 4let obj = {test1: test1, test2: test2}; 5//Shorthand 6let obj = {test1, test2};
23. 字符串转换为数字
1//Longhand 2let test1 = parseInt('123'); 3let test2 = parseFloat('12.3'); 4//Shorthand 5let test1 = +'123'; 6let test2 = +'12.3';
24. 解构赋值缩写法
1//longhand 2const test1 = this.data.test1; 3const test2 = this.data.test2; 4const test2 = this.data.test3; 5//shorthand 6const { test1, test2, test3 } = this.data;
25. Array.find 缩写法
当我们需要在一个对象数组中按属性值查找特定对象时,find 方法很有用。
1const data = [{ 2 type: 'test1', 3 name: 'abc' 4 }, 5 { 6 type: 'test2', 7 name: 'cde' 8 }, 9 { 10 type: 'test1', 11 name: 'fgh' 12 }, 13]function findtest1(name) { 14 for (let i = 0; i < data.length; ++i) { 15 if (data[i].type === 'test1' && data[i].name === name) { 16 return data[i]; 17 } 18 } 19} 20//Shorthand 21filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh'); 22console.log(filteredData); // { type: 'test1', name: 'fgh' }
26. 查询条件缩写法
如果我们要检查类型,并根据类型调用不同的函数,我们既可以使用多个 else if 语句,也可以使用 switch,除此之外,如果有缩写法,代码会是怎么样呢?
1// Longhand 2if (type === 'test1') { 3 test1(); 4} 5else if (type === 'test2') { 6 test2(); 7} 8else if (type === 'test3') { 9 test3(); 10} 11else if (type === 'test4') { 12 test4(); 13} else { 14 throw new Error('Invalid value ' + type); 15} 16// Shorthand 17var types = { 18 test1: test1, 19 test2: test2, 20 test3: test3, 21 test4: test4 22}; 23 24var func = types[type]; 25(!func) && throw new Error('Invalid value ' + type); func();
27. 按位非和 indexOf 缩写法
我们以查找特定值为目的迭代一个数组,通常用到 indexOf() 方法。
1//longhand 2if(arr.indexOf(item) > -1) { // item found 3} 4if(arr.indexOf(item) === -1) { // item not found 5} 6//shorthand 7if(~arr.indexOf(item)) { // item found 8} 9if(!~arr.indexOf(item)) { // item not found 10}
对除 -1 外的任何数进行 按位非(~) 运算都会返回真值。把按位非的结果再次进行逻辑取反就是 !~,这非常简单。或者我们也可以使用 includes() 函数:
1if (arr.includes(item)) { 2// true if the item found 3}
28. Object.entries()
该特性可以把对象转换成一个由若干对象组成的数组。
1const data = { test1: 'abc', test2: 'cde', test3: 'efg' }; 2const arr = Object.entries(data); 3console.log(arr);/** Output: 4[ [ 'test1', 'abc' ], 5 [ 'test2', 'cde' ], 6 [ 'test3', 'efg' ] 7] 8**/
29. Object.values()
这也是 ES8 中介绍的一个新特性,它的功能与 Object.entries() 类似,但没有其核心功能:
1const data = { test1: 'abc', test2: 'cde' }; 2const arr = Object.values(data); 3console.log(arr);/** Output: 4[ 'abc', 'cde'] 5**/
30. 两个位运算符缩写
(两个按位非运算符只适用于 32 位整型)
1// Longhand 2Math.floor(1.9) === 1 // true 3 4// Shorthand 5~~1.9 === 1 // true
31. 把一个字符串重复多次
我们可以使用 for 循环把一个字符串反复输出多次,那这种功能有没有缩写法呢?
1//longhand 2let test = ''; 3for(let i = 0; i < 5; i ++) { 4 test += 'test '; 5} 6console.log(str); // test test test test test 7//shorthand 8'test '.repeat(5);
32. 找出一个数组中最大和最小的值
1const arr = [1, 2, 3]; 2Math.max(…arr); // 3 3Math.min(…arr); // 1
33. 获取字符串中的字符
1let str = 'abc'; 2//Longhand 3str.charAt(2); // c 4//Shorthand 5//注意:如果事先知道目标字符在字符串中的索引,我们可以直接使用该索引值。如果索引值不确定,运行时就有可能抛出 undefined。 6str[2]; // c
34. 幂运算的缩写法
指数幂函数的缩写法:
1//longhand 2Math.pow(2,3); // 8 3//shorthand 42**3 // 8
