標籤:.com localhost obj 架構 require 傳遞值 操作 script ram
博主說:對於任何基於 JavaScript 的開發人員來說,這絕對是一篇必讀的文章,乃提升開發效率之神器也。
本文
js
1. 三元運算子
當你想用一行代碼來寫if...else語句的時候,使用三元操作符是非常好的選擇,例如:
const x = 20;
let answer;
if (x > 10) {
answer = ‘is greater‘;
} else {
可以簡寫為:
const answer = x > 10 ? ‘is greater‘ : ‘is lesser‘;
1
1
也可以嵌套if語句:
const big = x > 10 ? " greater 10" : x
1
1
2. 簡寫短路求值
當給一個變數分配另一個值的時候,你可能想確定初值不是null,undefined或空值。這時,你可以寫一個多重條件的if語句:
if (variable1 !== null || variable1 !== undefined || variable1 !== ‘‘) {
let variable2 = variable1;
或者可以使用短路求值的方法:
const variable2 = variable1 || ‘new‘;
1
1
3. 簡寫變數聲明
在定義函數的時候,你可能需要先聲明多個變數,例如:
let x;
let y;
這時,你可以使用簡寫的方式節省很多時間和空間,即同時聲明多個變數:
let x, y, z=3;
1
1
4. 簡寫 if 執行條件
這可能微不足道,但值得一提。在你做if條件檢查的時候,其賦值操作可以省略,例如:
if (likeJavaScript === true)
1
1
可以簡寫為:
if (likeJavaScript)
1
1
只有當likeJavaScript是真值的時候,以上兩個語句才可以替換。如果判斷假值,例如:
let a;
if ( a !== true ) {
// do something...
可以簡寫為:
let a;
if ( !a ) {
// do something...
5. 簡寫 JavaScript 迴圈方法
當你想使用純 javascript 而不依賴外庫(例如jQuery)的時候,這是非常有用的。
for (let i = 0; i < allImgs.length; i++)
1
1
可以簡寫為:
for (let index in allImgs)
1
1
也可以使用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. 短路求值
如果想通過判斷參數是否為null或者undefined來分配預設值的話,我們不需要寫六行代碼,而是可以使用一個短路邏輯運算子,只用一行代碼來完成相同的操作。例如:
let dbHost;
if (process.env.DB_HOST) {
dbHost = process.env.DB_HOST;
} else {
dbHost = ‘localhost‘;
6
可以簡寫為:
const dbHost = process.env.DB_HOST |www.wmyl110.com| ‘localhost‘;
1
1
7. 十進位指數
當數位尾部為很多的零時(如10000000),咱們可以使用指數(1e7)來代替這個數字,例如:
for (let i = 0; i < 10000; i++) {}
1
1
可以簡寫為:
for (let i = 0; i < 1e7; i++) {}
// 下面都是返回 true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
8. 簡寫對象屬性
在 JavaScript 中定義對象很簡單,而且ES6提供了一個更簡單的指派至屬性的方法。如果屬性名稱與key值相同,例如:
const obj = { x:x, y:y };
1
1
則可以簡寫為:
const obj = { x, y };
1
1
9. 簡寫箭頭函數
傳統函數很容易讓人理解和編寫,但是當它嵌套在另一個函數中的時候,它就會變得冗長和混亂。例如:
function sayHello(name) {
console.log(‘Hello‘, name);
}
setTimeout(function() {
console.log(‘Loaded‘)
}, 2000);
list.forEach(function(item) {
console.log(item);
這時,可以簡寫為:
sayHello = name => console.log(‘Hello‘, name);
setTimeout(() => console.log(‘Loaded‘), 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 ) =>www.chuangyed.com (l * w * h);
volume(2) // output: 24
12. 字串模板
你是不是厭倦了使用+將多個變數轉換為字串?有沒有更簡單的方法呢?如果你能夠使用ES6,那麼很幸運,你僅需使用反引號並將變數置於${}之中即可。例如:
const welcome = ‘You have logged in as ‘ + first + ‘ ‘ + last + ‘.‘
const db = ‘http://‘ + host + ‘:‘ + port + ‘/‘ + database;
可以簡寫為:
const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;
13. 簡寫賦值方法
如果你正在使用任何流行的 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 } www.wmyl15.com/
3
也可以分配變數名:
// 最後一個變數名為 contact
const { store, form, loading, errors, entity:contact } = this.props;
14. 簡寫多行字串
如果你曾發現自己需要在代碼中編寫多行字串,那麼這估計就是你編寫它們的方法,即在輸出的多行字串間用+來拼接:
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‘
但是如果使用反引號,你就可以達到簡寫的目的:
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. 擴充運算子
在ES6中,包括擴充運算子,它可以使你的操作更簡單,例如:
// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].www.wmyL119.cn 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語句拋出undefined的錯誤,或者使用“強制參數”的方法。例如:
function foo(bar) {
if(bar === undefined) {
throw new Error(‘Missing www.wmyl11.com parameter!‘);
}
return bar;
可以簡寫為:
mandatory = () => {
throw new Error(‘Missing www.zbcppt.com parameter!‘);
}
foo = (bar = mandatory()) => {
17. Array.find 簡寫
如果你曾負責編寫 JavaScript 中的find函數,那麼你很有可能使用了for迴圈。在此,介紹ES6中一個名為find()的數組函數。
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];
可以簡寫為:
pet = pets.find(pet => pet.type ===‘Dog‘ && pet.name === ‘Tommy‘);
console.log(pet); // { type: ‘Dog‘, name: ‘Tommy‘ }
1
2
1
2
18. 簡寫 Object[key]
你知道Foo.bar也可以寫成Foo[‘bar‘]嗎?起初,似乎沒有什麼理由讓你這樣寫。然而,這個符號給了你編寫可重用代碼的基礎。考慮如下簡化的驗證函式樣本:
function validate(values) {
if(!values.first)
return false;
if(!values.last)
return false;
return true;
}
console.log(validate({first:‘Bruce‘,last:‘Wayne‘})); // 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:‘Bruce‘})); // false
console.log(validate(schema, {first:‘Bruce‘,last:‘Wayne‘})); // true
現在我們就有了一個可以在所有的form中重用的驗證函式,而無需為每個form編寫其自訂的驗證函式啦!
19. 簡寫雙重按位非運算子
按位元運算符絕對是你初學 JavaScript 時瞭解的但一直沒有用武之地的運算子。因為如果不處理二進位,誰會沒事操作0和1呢?但是,雙重按位非運算子非常實用,例如你可以使用它來替代floor()函數,而且與其他相同的操作相比,按位元運算符的操作速度更快。
Math.floor(4.9) === 4 //true
1
1
可以簡寫為:
~~4.9 === 4 //true
20. Suggest One of U?
我很喜歡這些簡寫的方法,也希望能找到更多的簡寫方法,如果您知道的話,請在此留言,非常感謝!
翻譯聲明:本文源自「sitepoint」,19+ JavaScript Shorthand Coding Techniques。
19+ JavaScript 常用的簡寫技巧