欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

分享19個(gè)JavaScript 有用的簡(jiǎn)寫(xiě)寫(xiě)法

 更新時(shí)間:2017年07月07日 12:14:46   投稿:mdxy-dxy  
最近很火的一篇來(lái)自國(guó)外的文章,js的簡(jiǎn)寫(xiě)寫(xiě)法一定程度上可以提高你的js書(shū)寫(xiě)水平對(duì)于js的理解也會(huì)更近一步

原文鏈接,最近很火的一篇文章

This really is a must read for any JavaScript-based developer. I have written this article as a vital source of reference for learning shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what is going on I have included the longhand versions to give some coding perspective.

這篇文章對(duì)于任何基于javascript開(kāi)發(fā)人員是必須要看的文章了,我寫(xiě)這篇文章是學(xué)習(xí)多年來(lái)我所熟悉的JavaScript 簡(jiǎn)寫(xiě)方法,為幫助大家學(xué)習(xí)理解特整理了一些非簡(jiǎn)寫(xiě)的寫(xiě)法。

June 14th, 2017: This article was updated to add new shorthand tips based on ES6. If you want to learn more about the changes in ES6, sign up for SitePoint Premium and check out our screencast A Look into ES6

本文來(lái)源于多年的 JavaScript 編碼技術(shù)經(jīng)驗(yàn),適合所有正在使用 JavaScript 編程的開(kāi)發(fā)人員閱讀。

本文的目的在于幫助大家更加熟練的運(yùn)用 JavaScript 語(yǔ)言來(lái)進(jìn)行開(kāi)發(fā)工作。

文章將分成初級(jí)篇和高級(jí)篇兩部分,分別進(jìn)行介紹。

1.三元操作符

當(dāng)想寫(xiě)if...else語(yǔ)句時(shí),使用三元操作符來(lái)代替。

普通寫(xiě)法:

const x = 20;
let answer;
if (x > 10) {
 answer = 'is greater';
} else {
 answer = 'is lesser';
}

簡(jiǎn)寫(xiě):

const answer = x > 10 ? 'is greater' : 'is lesser';

也可以嵌套if語(yǔ)句:

const big = x > 10 ? " greater 10" : x

2.短路求值簡(jiǎn)寫(xiě)方式

當(dāng)給一個(gè)變量分配另一個(gè)值時(shí),想確定源始值不是null,undefined或空值。可以寫(xiě)撰寫(xiě)一個(gè)多重條件的if語(yǔ)句。

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
 let variable2 = variable1;
}

或者可以使用短路求值方法:

const variable2 = variable1 || 'new';

3.聲明變量簡(jiǎn)寫(xiě)方法

let x;
let y;
let z = 3;

簡(jiǎn)寫(xiě)方法:

let x, y, z=3;

4.if存在條件簡(jiǎn)寫(xiě)方法

if (likeJavaScript === true)

簡(jiǎn)寫(xiě):

if (likeJavaScript)

只有l(wèi)ikeJavaScript是真值時(shí),二者語(yǔ)句才相等

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

let a;
if ( a !== true ) {
// do something...
}

簡(jiǎn)寫(xiě):

let a;
if ( !a ) {
// do something...
}

5.JavaScript循環(huán)簡(jiǎn)寫(xiě)方法

for (let i = 0; i < allImgs.length; i++)

簡(jiǎn)寫(xiě):

for (let index in allImgs)

也可以使用Array.forEach

function logArrayElements(element, index, array) {
 console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

6.短路評(píng)價(jià)

給一個(gè)變量分配的值是通過(guò)判斷其值是否為nullundefined,則可以:

let dbHost;
if (process.env.DB_HOST) {
 dbHost = process.env.DB_HOST;
} else {
 dbHost = 'localhost';
}

簡(jiǎn)寫(xiě):

const dbHost = process.env.DB_HOST || 'localhost';

7.十進(jìn)制指數(shù)

當(dāng)需要寫(xiě)數(shù)字帶有很多零時(shí)(如10000000),可以采用指數(shù)(1e7)來(lái)代替這個(gè)數(shù)字:

for (let i = 0; i < 10000000; i++) {}

簡(jiǎn)寫(xiě):

for (let i = 0; i < 1e7; i++) {}

// 下面都是返回true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

8.對(duì)象屬性簡(jiǎn)寫(xiě)

如果屬性名與key名相同,則可以采用ES6的方法:

const obj = { x:x, y:y };

簡(jiǎn)寫(xiě):

const obj = { x, y };

9.箭頭函數(shù)簡(jiǎn)寫(xiě)

傳統(tǒng)函數(shù)編寫(xiě)方法很容易讓人理解和編寫(xiě),但是當(dāng)嵌套在另一個(gè)函數(shù)中,則這些優(yōu)勢(shì)就蕩然無(wú)存。

function sayHello(name) {
 console.log('Hello', name);
}

setTimeout(function() {
 console.log('Loaded')
}, 2000);

list.forEach(function(item) {
 console.log(item);
});

簡(jiǎn)寫(xiě):

sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));

10.隱式返回值簡(jiǎn)寫(xiě)

經(jīng)常使用return語(yǔ)句來(lái)返回函數(shù)最終結(jié)果,一個(gè)單獨(dú)語(yǔ)句的箭頭函數(shù)能隱式返回其值(函數(shù)必須省略{}為了省略return關(guān)鍵字)

為返回多行語(yǔ)句(例如對(duì)象字面表達(dá)式),則需要使用()包圍函數(shù)體。

function calcCircumference(diameter) {
 return Math.PI * diameter
}

var func = function func() {
 return { foo: 1 };
};

簡(jiǎn)寫(xiě):

calcCircumference = diameter => (
 Math.PI * diameter;
)

var func = () => ({ foo: 1 });

11.默認(rèn)參數(shù)值

為了給函數(shù)中參數(shù)傳遞默認(rèn)值,通常使用if語(yǔ)句來(lái)編寫(xiě),但是使用ES6定義默認(rèn)值,則會(huì)很簡(jiǎn)潔:

function volume(l, w, h) {
 if (w === undefined)
 w = 3;
 if (h === undefined)
 h = 4;
 return l * w * h;
}

簡(jiǎn)寫(xiě):

volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24

12.模板字符串

傳統(tǒng)的JavaScript語(yǔ)言,輸出模板通常是這樣寫(xiě)的。

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

ES6可以使用反引號(hào)和${}簡(jiǎn)寫(xiě):

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

13.解構(gòu)賦值簡(jiǎn)寫(xiě)方法

在web框架中,經(jīng)常需要從組件和API之間來(lái)回傳遞數(shù)組或?qū)ο笞置嫘问降臄?shù)據(jù),然后需要解構(gòu)它

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;

簡(jiǎn)寫(xiě):

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

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

也可以分配變量名:

const { store, form, loading, errors, entity:contact } = this.props;
//最后一個(gè)變量名為contact

14.多行字符串簡(jiǎn)寫(xiě)

需要輸出多行字符串,需要使用+來(lái)拼接:

const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
 + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
 + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
 + 'veniam, quis nostrud exercitation ullamco laboris\n\t'
 + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
 + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'

使用反引號(hào),則可以達(dá)到簡(jiǎn)寫(xiě)作用:

const lorem = `Lorem ipsum dolor sit amet, consectetur
 adipisicing elit, sed do eiusmod tempor incididunt
 ut labore et dolore magna aliqua. Ut enim ad minim
 veniam, quis nostrud exercitation ullamco laboris
 nisi ut aliquip ex ea commodo consequat. Duis aute
 irure dolor in reprehenderit in voluptate velit esse.`

15.擴(kuò)展運(yùn)算符簡(jiǎn)寫(xiě)

擴(kuò)展運(yùn)算符有幾種用例讓JavaScript代碼更加有效使用,可以用來(lái)代替某個(gè)數(shù)組函數(shù)。

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

簡(jiǎn)寫(xiě):

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

不像concat()函數(shù),可以使用擴(kuò)展運(yùn)算符來(lái)在一個(gè)數(shù)組中任意處插入另一個(gè)數(shù)組。

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

也可以使用擴(kuò)展運(yùn)算符解構(gòu):

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

16.強(qiáng)制參數(shù)簡(jiǎn)寫(xiě)

JavaScript中如果沒(méi)有向函數(shù)參數(shù)傳遞值,則參數(shù)為undefined。為了增強(qiáng)參數(shù)賦值,可以使用if語(yǔ)句來(lái)拋出異常,或使用強(qiáng)制參數(shù)簡(jiǎn)寫(xiě)方法。

function foo(bar) {
 if(bar === undefined) {
 throw new Error('Missing parameter!');
 }
 return bar;
}

簡(jiǎn)寫(xiě):

mandatory = () => {
 throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
 return bar;
}

17.Array.find簡(jiǎn)寫(xiě)

想從數(shù)組中查找某個(gè)值,則需要循環(huán)。在ES6中,find()函數(shù)能實(shí)現(xiàn)同樣效果。

const pets = [
 { type: 'Dog', name: 'Max'},
 { type: 'Cat', name: 'Karl'},
 { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
 for(let i = 0; i<pets.length; ++i) {
 if(pets[i].type === 'Dog' && pets[i].name === name) {
 return pets[i];
 }
 }
}

簡(jiǎn)寫(xiě):

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18.Object[key]簡(jiǎn)寫(xiě)

考慮一個(gè)驗(yàn)證函數(shù)

function validate(values) {
 if(!values.first)
 return false;
 if(!values.last)
 return false;
 return true;
}

console.log(validate({first:'Bruce',last:'Wayne'})); // true

假設(shè)當(dāng)需要不同域和規(guī)則來(lái)驗(yàn)證,能否編寫(xiě)一個(gè)通用函數(shù)在運(yùn)行時(shí)確認(rèn)?

// 對(duì)象驗(yàn)證規(guī)則
const schema = {
 first: {
 required:true
 },
 last: {
 required:true
 }
}

// 通用驗(yàn)證函數(shù)
const validate = (schema, values) => {
 for(field in schema) {
 if(schema[field].required) {
 if(!values[field]) {
 return false;
 }
 }
 }
 return true;
}


console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

現(xiàn)在可以有適用于各種情況的驗(yàn)證函數(shù),不需要為了每個(gè)而編寫(xiě)自定義驗(yàn)證函數(shù)了

19.雙重非位運(yùn)算簡(jiǎn)寫(xiě)

有一個(gè)有效用例用于雙重非運(yùn)算操作符??梢杂脕?lái)代替Math.floor(),其優(yōu)勢(shì)在于運(yùn)行更快,可以閱讀此文章了解更多位運(yùn)算。

Math.floor(4.9) === 4 //true

簡(jiǎn)寫(xiě)

~~4.9 === 4 //true

到此就完成了相關(guān)的介紹,推薦大家繼續(xù)看下面的相關(guān)文章

相關(guān)文章

  • Asp.Net之JS生成分頁(yè)條的方法

    Asp.Net之JS生成分頁(yè)條的方法

    下面小編就為大家?guī)?lái)一篇Asp.Net之JS生成分頁(yè)條的方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-11-11
  • JavaScript實(shí)現(xiàn)前端網(wǎng)頁(yè)版倒計(jì)時(shí)

    JavaScript實(shí)現(xiàn)前端網(wǎng)頁(yè)版倒計(jì)時(shí)

    這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)前端網(wǎng)頁(yè)版倒計(jì)時(shí),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-03-03
  • js異步編程小技巧詳解

    js異步編程小技巧詳解

    這篇文章主要介紹了js異步編程技巧,使用計(jì)數(shù)器的方式,每完成一個(gè)請(qǐng)求計(jì)數(shù)器加1 當(dāng)計(jì)數(shù)器等于2時(shí)執(zhí)行回調(diào)邏輯,兩個(gè)http并行發(fā)送,從而極大的提高了效率,需要的朋友可以參考下
    2017-08-08
  • 關(guān)于JS模塊化的知識(shí)點(diǎn)分享

    關(guān)于JS模塊化的知識(shí)點(diǎn)分享

    在本篇文章里小編給大家整理的是關(guān)于JS模塊化的知識(shí)點(diǎn)分享,有需要的朋友們可以學(xué)習(xí)下。
    2019-10-10
  • javascript 對(duì)象比較實(shí)現(xiàn)代碼

    javascript 對(duì)象比較實(shí)現(xiàn)代碼

    js對(duì)象比較實(shí)現(xiàn)代碼。
    2009-04-04
  • JS驗(yàn)證input輸入框(字母,數(shù)字,符號(hào),中文)

    JS驗(yàn)證input輸入框(字母,數(shù)字,符號(hào),中文)

    本文主要介紹了JS驗(yàn)證input輸入框(字母,數(shù)字,符號(hào),中文)的方法。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧
    2017-03-03
  • javascript中的new使用

    javascript中的new使用

    javascript是基于原型(Prototype based)的面向?qū)ο蟮恼Z(yǔ)言,這點(diǎn)不同于我們熟悉的.NET,Java語(yǔ)言,是基于類(lèi)模式(Class based)。
    2010-03-03
  • Bootstrap table表格初始化表格數(shù)據(jù)的方法

    Bootstrap table表格初始化表格數(shù)據(jù)的方法

    這篇文章主要介紹了Bootstrap-table表格初始化表格數(shù)據(jù)的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-07-07
  • Javascript中typeof 用法小結(jié)

    Javascript中typeof 用法小結(jié)

    JavaScript中的typeof其實(shí)非常復(fù)雜,他有六種返回的數(shù)據(jù)類(lèi)型,它可以用來(lái)做很多事情,但同時(shí)也有很多怪異的表現(xiàn).本文列舉出了它的多個(gè)用法,有需要的小伙伴可以參考下。
    2015-05-05
  • Javascript循環(huán)綁定事件的示例代碼

    Javascript循環(huán)綁定事件的示例代碼

    我們先看一個(gè)關(guān)于Javascript利用循環(huán)綁定事件的例子
    2008-10-10

最新評(píng)論