Habilidades de optimización de código JS imperdibles (actualizadas continuamente)

1. Instrucción if con múltiples condiciones

Coloque múltiples valores en una matriz, luego llame al método include de la matriz.

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}
复制代码

2. Simplificar si es cierto... si no

Para las condiciones if-else que no contienen una lógica grande, se pueden usar los siguientes atajos. Podemos lograr esta simplificación simplemente usando el operador ternario.

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//或者我们也可以直接用
let test = x > 10;
console.log(test);
复制代码

Esto se puede hacer si hay condiciones anidadas.

let x = 300,
test2 = (x > 100) ? 'greater than 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
复制代码

3. Declarar variables

Esta abreviatura se puede usar cuando queremos declarar dos variables con el mismo valor o el mismo tipo.

//Longhand 
let test1;
let test2 = 1;
//Shorthand 
let test1, test2 = 1;
复制代码

4. Comprobación de valor nulo, indefinido y nulo

Cuando creamos nuevas variables, a veces queremos verificar si la variable a la que se hace referencia no es nula o no está definida. JavaScript tiene un buen atajo para implementar este tipo de verificación.

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
复制代码

5. verificación nula y asignación predeterminada

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // 输出 ""
复制代码

6. Comprobación indefinida y asignación predeterminada.

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // 输出 ""
复制代码

Comprobación general de valores

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // 输出: 'test'
复制代码

Además, para los puntos 4, 5 y 6 anteriores, se puede utilizar el operador ??.

Si el valor de la izquierda es nulo o indefinido, se devuelve el valor de la derecha. De forma predeterminada, devolverá el valor de la izquierda.

const test= null ?? 'default';
console.log(test);
// 输出结果: "default"
const test1 = 0 ?? 2;
console.log(test1);
// 输出结果: 0
复制代码

7. Asigna valores a múltiples variables

Este truco es muy útil cuando queremos asignar valores a múltiples variables diferentes.

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];
复制代码

8. Operador de asignación simple

Durante la programación, tratamos con una gran cantidad de operadores aritméticos. Este es uno de los trucos útiles de los operadores de asignación de variables de JavaScript.

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
复制代码

9. si para determinar si el valor existe

Es un truco útil común que todos usamos, y aún vale la pena mencionarlo aquí.

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //检查空字符串、null或者undefined
if (test1)
复制代码

Nota: Si test1 tiene un valor, se ejecutará la lógica después de If. Este operador se usa principalmente para verificaciones nulas o indefinidas.

10. El operador && para múltiples condiciones

Para llamar a una función solo cuando la variable es verdadera, use el operador &&.

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();
复制代码

11. por cada bucle

Este es un truco común de simplificación de bucles.

// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or  for (let i of testData)
复制代码

Iterar sobre cada variable de la matriz.

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. Devolución después de la comparación

También podemos usar comparaciones en la declaración de devolución, lo que reduce 5 líneas de código a 1.

// 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. Funciones de flecha

//Longhand 
function add(a, b) { 
   return a + b; 
} 
//Shorthand 
const add = (a, b) => a + b;
复制代码

Más ejemplos:

function callMe(name) {
  console.log('Hello', name);
}
callMe = name => console.log('Hello', name);
复制代码

14. Llamadas de funciones cortas

Podemos usar el operador ternario para implementar múltiples llamadas a funciones.

// 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. cambiar la simplificación

Podemos almacenar condiciones en objetos clave-valor y llamarlos en función de las condiciones.

// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // ...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();
复制代码

16. 隐式返回

通过使用箭头函数,我们可以直接返回值,不需要 return 语句。

//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() //输出结果: 3
复制代码

19. 延展操作符简化

//longhand
// 使用concat连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//shorthand
// 连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
复制代码

我们也可以使用延展操作符进行克隆。

//longhand
// 克隆数组
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand
//克隆数组
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};
复制代码

23. 将字符串转成数字

//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. 数组 find 简化

当我们有一个对象数组,并想根据对象属性找到特定对象,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. 条件查找简化

如果我们要基于不同的类型调用不同的方法,可以使用多个 else if 语句或 switch,但有没有比这更好的简化技巧呢?

// 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 的按位操作简化

在查找数组的某个值时,我们可以使用 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
}
复制代码

按位 ( ~ ) 运算符将返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函数。

if (arr.includes(item)) { 
// 如果找到项目,则为true
}
复制代码

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()

这也是 ES8 中引入的一个新特性,它的功能类似于 Object.entries(),只是没有键。

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
复制代码

30. 双重按位操作

// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
复制代码

31. 重复字符串多次

为了重复操作相同的字符,我们可以使用 for 循环,但其实还有一种简便的方法。

//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 
str[2]; // c
复制代码

34. 指数幂简化

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8
复制代码

————————————————————————————

以后遇到了再进行补充~~~~

Supongo que te gusta

Origin juejin.im/post/7078575191244144670
Recomendado
Clasificación