当前位置 博文首页 > 程序员石磊:javascript代码这样写,美得像诗一样!

    程序员石磊:javascript代码这样写,美得像诗一样!

    作者:[db:作者] 时间:2021-07-04 12:53

    用简介的代码实现复杂的功能,看上去就很美,talk is cheap,show me the code!
    在这里插入图片描述

    1.如果有多个条件

    我们可以在数组中存储多个值,并且可以使用数组include方法。

    //long
    if (x === 'hello' || x === 'hola' || x === 'hallo' || x ==='hej') {
    //logic
    }
    //short
    if (['hello', 'hola', 'hallo', 'hej'].includes(x)) {
    //logic
    }
    

    2.如果为true…否则为简写

    当我们具有不包含更大逻辑的if-else条件时,这是一个更大的捷径。我们可以简单地使用三元运算符来实现该功能。

    // long
    let test= boolean;
    if (x > 100) {
    test = true;
    } else {
    test = false;
    }
    // short
    let test = (x > 10) ? true : false;
    //or we can simply use
    let test = x > 10;
    console.log(test);
    

    3.空,未定义,空检查

    当我们确实创建新变量时,有时我们想检查所引用变量的值是否不为null或未定义。JavaScript确实具有实现这些功能的非常好的捷径。

    // Longhand
    if (first !== null || first !== undefined || first !== '') {
    let second = first;
    }
    // Shorthand
    let second = first|| '';
    

    4.空值检查和分配默认值

    let first = null,
    let second = first || '';
    console.log("null check", test2); // output will be ""
    
    

    5.未定义值检查和分配默认值

    let first= undefined,
    let second = first || '';
    console.log("undefined check", test2); // output will be ""
    
    

    6.foreach循环简写

    This is a useful short hand for iteration
    // Longhand
    for (var i = 0; i < testData.length; i++)
    
    // Shorthand
    for (let i in testData) or  for (let i of testData)
    Array for each variable
    function testData(element, index, array) {
      console.log('test[' + index + '] = ' + element);
    }
    
    [11, 24, 32].forEach(testData);
    // prints: test[0] = 11, test[1] = 24, test[2] = 32
    
    

    7.比较返回

    在return语句中使用比较,将避免我们的5行代码减少到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');
    }
    
    

    8.短函数调用

    我们可以使用三元运算符实现这些类型的功能。

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

    9.切换简写

    我们可以将条件保存在键值对象中,并可以根据条件使用。

    // 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[anything] && data[anything]();
    
    

    10.多行字符串简写

    当我们在代码中处理多行字符串时,我们可以这样做:

    //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`
    
    

    11,隐含返回简写

    使用箭头功能,我们可以直接返回值,而不必编写return语句。

    //longhand
    function getArea(diameter) {
      return Math.PI * diameter
    }
    //shorthand
    getArea = diameter => (
      Math.PI * diameter;
    )
    
    

    12.查询条件简写

    如果我们有代码来检查类型,并且根据类型需要调用不同的方法,我们可以选择使用多个else if或进行切换,但是如果我们的速记比这更好呢?

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

    13.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' ]
    ]
    **/
    
    

    14. Object.values()

    这也是ES8中引入的一项新功能,该功能执行与Object.entries()类似的功能,但没有关键部分:

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

    15.重复一个字符串多次

    要一次又一次地重复相同的字符,我们可以使用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);
    
    

    16.数值分隔符

    现在,您只需使用_即可轻松分隔数字。这将使从事大量工作的开发人员的生活更加轻松。

    //old syntax
    let number = 98234567
    
    //new syntax
    let number = 98_234_567
    
    
    cs