日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
19個(gè)JavaScript有用的簡寫技術(shù)

1.三元操作符

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

 
 
 
 
  1. const x = 20;
  2. let answer;
  3. if (x > 10) {
  4.     answer = 'is greater';
  5. } else {
  6.     answer = 'is lesser';
  7. }

簡寫:

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

也可以嵌套if語句:

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

2.短路求值簡寫方式

當(dāng)給一個(gè)變量分配另一個(gè)值時(shí),想確定源始值不是null,undefined或空值??梢詫懽珜懸粋€(gè)多重條件的if語句。

 
 
 
 
  1. if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  2.      let variable2 = variable1;
  3. }

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

 
 
 
 
  1. const variable2 = variable1 || 'new';

3.聲明變量簡寫方法

 
 
 
 
  1. let x;
  2. let y;
  3. let z = 3;

簡寫方法:

 
 
 
 
  1. let x, y, z=3;

4.if存在條件簡寫方法

 
 
 
 
  1. if (likeJavaScript === true)

簡寫:

 
 
 
 
  1. if (likeJavaScript)

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

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

 
 
 
 
  1. let a;
  2. if ( a !== true ) {
  3. // do something...
  4. }

簡寫:

 
 
 
 
  1. let a;
  2. if ( !a ) {
  3. // do something...
  4. }

5.JavaScript循環(huán)簡寫方法

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

簡寫:

 
 
 
 
  1. for (let index in allImgs)

也可以使用Array.forEach:

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

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

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

 
 
 
 
  1. let dbHost;
  2. if (process.env.DB_HOST) {
  3.   dbHost = process.env.DB_HOST;
  4. } else {
  5.   dbHost = 'localhost';
  6. }

簡寫:

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

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

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

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

簡寫:

 
 
 
 
  1. for (let i = 0; i < 1e7; i++) {}
  2. // 下面都是返回true
  3. 1e0 === 1;
  4. 1e1 === 10;
  5. 1e2 === 100;
  6. 1e3 === 1000;
  7. 1e4 === 10000;
  8. 1e5 === 100000;

8.對(duì)象屬性簡寫

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

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

簡寫:

 
 
 
 
  1. const obj = { x, y };

9.箭頭函數(shù)簡寫

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

 
 
 
 
  1. function sayHello(name) {
  2.   console.log('Hello', name);
  3. }
  4. setTimeout(function() {
  5.   console.log('Loaded')
  6. }, 2000);
  7. list.forEach(function(item) {
  8.   console.log(item);
  9. });

簡寫:

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

10.隱式返回值簡寫

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

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

 
 
 
 
  1. function calcCircumference(diameter) {
  2.   return Math.PI * diameter
  3. }
  4. var func = function func() {
  5.   return { foo: 1 };
  6. };

簡寫:

 
 
 
 
  1. calcCircumference = diameter => (
  2.   Math.PI * diameter;
  3. var func = () => ({ foo: 1 });

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

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

 
 
 
 
  1. function volume(l, w, h) {
  2.   if (w === undefined)
  3.     w = 3;
  4.   if (h === undefined)
  5.     h = 4;
  6.   return l * w * h;
  7. }

簡寫:

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

12.模板字符串

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

 
 
 
 
  1. const welcome = 'You have logged in as ' + first + ' ' + last + '.'
  2. const db = 'http://' + host + ':' + port + '/' + database;

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

 
 
 
 
  1. const welcome = `You have logged in as ${first} ${last}`;
  2. const db = `http://${host}:${port}/${database}`;

13.解構(gòu)賦值簡寫方法

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

 
 
 
 
  1. const observable = require('mobx/observable');
  2. const action = require('mobx/action');
  3. const runInAction = require('mobx/runInAction');
  4. const store = this.props.store;
  5. const form = this.props.form;
  6. const loading = this.props.loading;
  7. const errors = this.props.errors;
  8. const entity = this.props.entity;

簡寫:

 
 
 
 
  1. import { observable, action, runInAction } from 'mobx';
  2. const { store, form, loading, errors, entity } = this.props;

也可以分配變量名:

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

14.多行字符串簡寫

需要輸出多行字符串,需要使用+來拼接:

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

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

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

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

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

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

簡寫:

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

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

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

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

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

16.強(qiáng)制參數(shù)簡寫

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

 
 
 
 
  1. function foo(bar) {
  2.   if(bar === undefined) {
  3.     throw new Error('Missing parameter!');
  4.   }
  5.   return bar;
  6. }

簡寫:

 
 
 
 
  1. mandatory = () => {
  2.   throw new Error('Missing parameter!');
  3. }
  4. foo = (bar = mandatory()) => {
  5.   return bar;
  6. }

17.Array.find簡寫

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

 
 
 
 
  1. const pets = [
  2.   { type: 'Dog', name: 'Max'},
  3.   { type: 'Cat', name: 'Karl'},
  4.   { type: 'Dog', name: 'Tommy'},
  5. ]
  6. function findDog(name) {
  7.   for(let i = 0; i
  8.     if(pets[i].type === 'Dog' && pets[i].name === name) {
  9.       return pets[i];
  10.     }
  11.   }
  12. }

簡寫:

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

18.Object[key]簡寫

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

 
 
 
 
  1. function validate(values) {
  2.   if(!values.first)
  3.     return false;
  4.   if(!values.last)
  5.     return false;
  6.   return true;
  7. }
  8. console.log(validate({first:'Bruce',last:'Wayne'})); // true

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

 
 
 
 
  1. // 對(duì)象驗(yàn)證規(guī)則
  2. const schema = {
  3.   first: {
  4.     required:true
  5.   },
  6.   last: {
  7.     required:true
  8.   }
  9. // 通用驗(yàn)證函數(shù)
  10. const validate = (schema, values) => {
  11.   for(field in schema) {
  12.     if(schema[field].required) {
  13.       if(!values[field]) {
  14.         return false;
  15.       }
  16.     }
  17.   }
  18.   return true;
  19. console.log(validate(schema, {first:'Bruce'})); // false
  20. console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

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

19.雙重非位運(yùn)算簡寫

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

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

簡寫:

 
 
 
 
  1. ~~4.9 === 4 //true 

網(wǎng)站標(biāo)題:19個(gè)JavaScript有用的簡寫技術(shù)
本文來源:http://m.5511xx.com/article/djheoee.html