首頁  >  文章  >  web前端  >  js的簡寫寫法介紹

js的簡寫寫法介紹

零下一度
零下一度原創
2017-07-09 09:39:422943瀏覽

最近很火的一篇來自國外的文章,js的簡寫寫法一定程度上可以提高你的js書寫水平對於js的理解也會更近一步

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

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 upearning 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.

#這篇文章對於任何基於javascript開發人員是必須要看的文章了,我寫這文章是學習多年來我所熟悉的JavaScript 簡寫方法,為幫助大家學習理解特整理了一些非簡寫的寫法。

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 Lookmium and check out Look the changes in ES6, sign up for SitePoint Lookmium and check out Lookmium and checkto inmourium and check out Lookm ESs

1.三元運算子

當想寫if...else語句時,使用三元運算子來取代。

普通寫法:


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

簡寫:


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

也可以嵌套if語句:


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

2.短路求值簡寫方式

當給一個變數分配另一個值時,想確定來源始值不是nullundefined或空值。可以寫出寫一個多重條件的if語句。


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

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


#
const variable2 = variable1 || 'new';

3.宣告變數簡寫方法


let x;
let y;
let z = 3;

簡寫方法:


#
let x, y, z=3;

4.if存在條件簡寫方法


if (likeJavaScript === true)

簡寫:


if (likeJavaScript)

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

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


##

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

簡寫:


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

5.JavaScript循環簡寫方法


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

簡寫:


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.短路評估

給一個變數分配的值是透過判斷其值是否為

nullundefined,則可以:


#

let dbHost;
if (process.env.DB_HOST) {
 dbHost = process.env.DB_HOST;
} else {
 dbHost = &#39;localhost&#39;;
}

簡寫:




##
const dbHost = process.env.DB_HOST || &#39;localhost&#39;;

7.十進位指數


當需要寫數字帶有很多零(如10000000),可以用指數(1e7)來取代這個數字:


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

簡寫:

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

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

8.物件屬性簡寫


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


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

簡寫:

const obj = { x, y };

#9.箭頭函數簡寫傳統函數編寫方法很容易讓人理解和編寫,但是當嵌套在另一個函數中,則這些優勢就蕩然無存。

function sayHello(name) {
 console.log(&#39;Hello&#39;, name);
}

setTimeout(function() {
 console.log(&#39;Loaded&#39;)
}, 2000);

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


#

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

10.隱含回傳值簡寫




#經常使用return語句來傳回函數最終結果,一個單獨語句的箭頭函數能隱含回傳其值(函數必須省略

{}

為了省略

return

關鍵字)

為傳回多行語句(例如物件字面

表達式),則需要使用()包圍函數體。


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

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

簡寫:

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

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

11.預設參數值


#為了給函數中參數傳遞預設值,通常使用if語句來編寫,但是使用ES6定義預設值,則會很簡潔:


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


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

12.模板字串

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


const welcome = &#39;You have logged in as &#39; + first + &#39; &#39; + last + &#39;.&#39;

const db = &#39;http://&#39; + host + &#39;:&#39; + port + &#39;/&#39; + database;

ES6可以使用反引號和

${}

簡寫:


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

const db = `http://${host}:${port}/${database}`;
##### ##13.解構賦值簡寫方法#########在web框架中,經常需要從元件和API之間來回傳遞數組或物件字面形式的數據,然後需要解構它####### ######
const observable = require(&#39;mobx/observable&#39;);
const action = require(&#39;mobx/action&#39;);
const runInAction = require(&#39;mobx/runInAction&#39;);

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 &#39;mobx&#39;;

const { store, form, loading, errors, entity } = this.props;
###也可以指派###變數名稱###:########## ##
const { store, form, loading, errors, entity:contact } = this.props;
//最后一个变量名为contact
######14.多行字串簡寫#########需要輸出多行字串,需要使用+來拼接:############
const lorem = &#39;Lorem ipsum dolor sit amet, consectetur\n\t&#39;
  + &#39;adipisicing elit, sed do eiusmod tempor incididunt\n\t&#39;
  + &#39;ut labore et dolore magna aliqua. Ut enim ad minim\n\t&#39;
  + &#39;veniam, quis nostrud exercitation ullamco laboris\n\t&#39;
  + &#39;nisi ut aliquip ex ea commodo consequat. Duis aute\n\t&#39;
  + &#39;irure dolor in reprehenderit in voluptate velit esse.\n\t&#39;
###使用反引號,則可以達到簡寫用:#############
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.扩展运算符简写

扩展运算符有几种用例让JavaScript代码更加有效使用,可以用来代替某个数组函数。


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

简写:


// 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()函数,可以使用扩展运算符来在一个数组中任意处插入另一个数组。


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

也可以使用扩展运算符解构:


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.强制参数简写

JavaScript中如果没有向函数参数传递值,则参数为undefined。为了增强参数赋值,可以使用if语句来抛出异常,或使用强制参数简写方法。


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

简写:


mandatory = () => {
 throw new Error(&#39;Missing parameter!&#39;);
}

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

17.Array.find简写

想从数组中查找某个值,则需要循环。在ES6中,find()函数能实现同样效果。


const pets = [
 { type: &#39;Dog&#39;, name: &#39;Max&#39;},
 { type: &#39;Cat&#39;, name: &#39;Karl&#39;},
 { type: &#39;Dog&#39;, name: &#39;Tommy&#39;},
]

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

简写:


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

18.Object[key]简写

考虑一个验证函数


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

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

假设当需要不同域和规则来验证,能否编写一个通用函数在运行时确认?


// 对象验证规则
const schema = {
 first: {
  required:true
 },
 last: {
  required:true
 }
}

// 通用验证函数
const validate = (schema, values) => {
 for(field in schema) {
  if(schema[field].required) {
   if(!values[field]) {
    return false;
   }
  }
 }
 return true;
}


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

现在可以有适用于各种情况的验证函数,不需要为了每个而编写自定义验证函数了

19.双重非位运算简写

有一个有效用例用于双重非运算操作符。可以用来代替Math.floor(),其优势在于运行更快,可以阅读此文章了解更多位运算。

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

简写

~~4.9 === 4 //true

到此就完成了相关的介绍,推荐大家继续看下面的相关文章

以上是js的簡寫寫法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn