34个JavaScript简写优化技术
1 多个条件
如果有多个条件,可以在数组中存储多个值。
//Longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//Shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
2 如果为真…否则简写
使用三元运算符来实现 if-else 简写
// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);
// 当我们有嵌套条件时,我们可以采用这种方式
let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
3 声明变量
要声明两个具有共同值或共同类型的变量时,可以使用此简写形式
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;
4 null, undefined,空检查
当我们创建新的变量时,有时我们想检查我们引用的变量的值是否为空或 undefined。
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
5 null 值检查和分配默认值
let test1 = null,
test2 = test1 || '';
console.log("null check", test2); // output will be ""
6 undefined 值检查和分配默认值
let test1 = undefined,
test2 = test1 || '';
console.log("undefined check", test2); // output will be ""
// 正常值检查
let test1 = 'test',
test2 = test1 || '';
console.log(test2); // output: 'test'
7 将值分配给多个变量
当我们处理多个变量并希望将不同的值分配给不同的变量时,此简写技术非常有用。
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
8 赋值运算符简写
我们在编程中处理很多算术运算符,这是将运算符分配给 JavaScript 变量的有用技术之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
9 如果存在
// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //it will check empty string,null and undefined too
if (test1)
10 多个条件的 AND 运算符
//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();
11 foreach 循环简写
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) // 或者 for (let i of testData)
// 每个变量的数组
function testData(element, index, array) {
console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32
12 return 中加入比较
// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe('test');
}
13 箭头函数
//Longhand
function add(a, b) {
return a + b;
}
//Shorthand
const add = (a, b) => a + b;
// 使用示例
function callMe(name) {
console.log('Hello', name);
}
callMe = name => console.log('Hello', name);
14 短函数调用
// Longhand
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// Shorthand
(test3 === 1? test1:test2)();
15 switch 简写
/ Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]();
16 隐式返回简写
//longhand
function calculate(diameter) {
return Math.PI * diameter
}
//shorthand
calculate = diameter => (
Math.PI * diameter;
)
17 小数基数指数
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) { ... }
18 默认参数值
//Longhand
function add(test1, test2) {
if (test1 === undefined)
test1 = 1;
if (test2 === undefined)
test2 = 2;
return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //output: 3
19 扩展运算符简写
//longhand
//joining arrays using concat
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//shorthand
//joining arrays
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
// 对于克隆,我们也可以使用扩展运算符。
//longhand - cloning arrays
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand - cloning arrays
const test1 = [1, 2, 3];
const test2 = [...test1];
20 模板文字
简化字符串中多个变量连接
//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;
21 多行字符串简写
//longhand
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`
22 对象属性分配
let test1 = 'a';
let test2 = 'b';
//Longhand
let obj = {test1: test1, test2: test2};
//Shorthand
let obj = {test1, test2};
22 将字符串转换成数字
//Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
//Shorthand
let test1 = +'123';
let test2 = +'12.3';
24 用解构简写
//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
25 用 Array.find 简写
const data = [
{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
]
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }
26 查找条件简写
// Longhand
if (type === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type);
func();
27 按位索引简写
当我们遍历数组以查找特定值时,我们确实使用 indexOf() 方法
//longhand
if(arr.indexOf(item) > -1) {
// item found
}
if(arr.indexOf(item) === -1) {
// item not found
}
//shorthand
if(~arr.indexOf(item)) {
// item found
}
if(!~arr.indexOf(item)) {
// item not found
}
28 Object.entries() 对象转换为对象数组
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/
29 Object.values() 对象值转数组
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
30 双按位简写
双重 NOT 按位运算符方法仅适用于 32 位整数
// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
31 重复一个字符串多次
//longhand
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test
//shorthand
'test '.repeat(5);
32 在数组中查找最大值和最小值
const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1
33 从字符串中获取字符
let str = 'abc';
//Longhand
str.charAt(2); // c
//Shorthand
//Note: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefined
str[2]; // c
34 数学指数幂函数的简写
//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8