JavaScript 如何書寫更優雅

JavaScript 如何書寫更優雅


平時在寫代碼邏輯時,有些代碼會很長,如何更簡潔的書寫,讓我們的代碼更優雅:

1、三目運算

當想寫 if...else 語句時,使用三目運算來代替。

var age = 20;

var tip;

if(age>18) {

tip ='你成年啦'

}else {

tip = '未成年嘍'

}

簡寫:

var tip = age>18 ? '你成年啦' : '未成年嘍';

var a = 1;

var b = 2;

var c = 3;

簡寫方法:

var a = 1, var b = 2, var c = 3;

if存在條件簡寫方法

if (flag === true)

簡寫:

if (flag)

只有flag是真值時,二者語句才相等。

如果判斷值不是真值,則可以這樣:

if (flag !== true)

簡寫:

if (!flag)

3.函數參數

給一個變量分配的值是通過判斷其值是否為null或undefined,則可以:

function action(num) {

var a;

if(num) {

a = num;

} else {

a = 10;

}

}

簡寫:

function action(num) {

var a = num || 10;

}

4.箭頭函數

箭頭函數相當於匿名函數,並且簡化了函數定義

var f = function(v){

return v;

};

f(2);

簡寫:

var f = v =>v; // 變量名 = 參數 = 函數體

5.模板字符串

傳統的JavaScript語言,輸出模板通常是這樣寫的。

$.each(data,function(index,item){ //index 索引 item 當前元素

$(".index-main ul").append('

  • '+

    ''+

    '<label>'+/<label>

    ''+item.product_uprice+''+

    ''+item.product_price+' '+

    ' '+

    '

  • ')

    });

    ES6簡寫:

    $.each(data,function(index,item){ //index 索引 item 當前元素

    $(".index-main ul").append(`

  • <label>

    ${item.product_uprice}

    ${item.product_price}

  • `)

    });

    6.解構賦值簡寫方法

    在web框架中,經常需要從組件和API之間來回傳遞數組或對象字面形式的數據,然後需要解構它。

    const observable = require('mobx/observable');

    const action = require('mobx/action');

    const runInAction = require('mobx/runInAction');

    const store = this.props.store;

    const form = this.props.form;

    const loading = this.props.loading;

    const errors = this.props.errors;

    const entity = this.props.entity;

    簡寫:

    import { observable, action, runInAction } from 'mobx';

    const { store, form, loading, errors, entity } = this.props;

    7.擴展運算符簡寫

    擴展運算符有幾種用例讓JavaScript代碼更加有效使用,可以用來代替某個數組函數。

    數組合並 concat concat() 方法用於連接兩個或多個數組。該方法不會改變現有的數組,而僅僅會返回被連接數組的一個副本。

    var arr1=['a','b','c','d'];

    var arr2=['e','f'];

    var arr1=arr1.concat(arr2);

    簡寫:

    ES6 擴展運算符 它用於把一個數組轉化為用逗號分隔的參數序列,它常用在不定參數個數時的函數調用

    var arr3 = [0, 1, 2];

    var arr4 = [4];

    var arr3 = [...arr3, ...arr4];

    感謝大家的支持,小編給粉絲們準備了書籍資料哦。麻煩轉發+關注。私信我“資料".


    分享到:


    相關文章: