JavaScript編碼小技巧分享
三元操作符
如果使用if...else語(yǔ)句,那么這是一個(gè)很好節(jié)省代碼的方式。
const x = 20;let big;if (x > 10) {big = true;} else {big = false;}//這樣寫...const big = x > 10 ? true : false;
Short-circuit Evaluation
分配一個(gè)變量值到另一個(gè)變量的時(shí)候,你可能想要確保變量不是null、undefined或空。你可以寫一個(gè)有多個(gè)if的條件語(yǔ)句或者Short-circuit Evaluation。
if (variable1 !== null || variable1 !== undefined || variable1 !== ’’) { let variable2 = variable1;}// 這樣寫const variable2 = variable1 || ’new’;
不要相信我,請(qǐng)先相信自己的測(cè)試(可以把下面的代碼粘貼在es6console)
let variable1;let variable2 = variable1 || ’’;console.log(variable2 === ’’); // truevariable1 = ’foo’;variable2 = variable1 || ’’;console.log(variable2); // foo
聲明變量
在函數(shù)中聲明變量時(shí),像下面這樣同時(shí)聲明多個(gè)變量可以節(jié)省你大量的時(shí)間和空間:
let x;let y;let x = 3;// or let x, y, z = 3;
如果存在
這可能是微不足道的,但值得提及。做“如果檢查”時(shí),賦值操作符有時(shí)可以省略。
if (likeJavaScript === true)//orif (likeJavaScript)
注:這兩種方法并不完全相同,簡(jiǎn)寫檢查只要likeJavaScript是true都將通過。
這有另一個(gè)示例。如果a不是true,然后做什么。
let a;if (a !== true) {// do something ...}//orlet a;if (!a) {// do something ...}
JavaScript的for循環(huán)
如果你只想要原生的JavaScript,而不想依賴于jQuery或Lodash這樣的外部庫(kù),那這個(gè)小技巧是非常有用的。
for (let i = 0; i < allImgs.length; i++)//orfor (let index in allImgs)
Array.forEach簡(jiǎn)寫:
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
對(duì)象屬性
定義對(duì)象文字(Object literals)讓JavaScript變得更有趣。ES6提供了一個(gè)更簡(jiǎn)單的辦法來(lái)分配對(duì)象的屬性。如果屬性名和值一樣,你可以使用下面簡(jiǎn)寫的方式。
const obj = {x: x, y: y};//orconst obj = {x, y};
箭頭函數(shù)
經(jīng)典函數(shù)很容易讀和寫,但它們確實(shí)會(huì)變得有點(diǎn)冗長(zhǎng),特別是嵌套函數(shù)中調(diào)用其他函數(shù)時(shí)還會(huì)讓你感到困惑。
function sayHello(name) {console.log(’Hello’, name);}setTimeout(function() {console.log(’Loaded’)}, 2000);list.forEach(function(item){console.log(item)})//orsayHello = name => console.log(’Hello’, name);setTimeout(() => console.log(’Loaded’), 2000);list.forEach(item => console.log(item));
隱式返回
return在函數(shù)中經(jīng)常使用到的一個(gè)關(guān)鍵詞,將返回函數(shù)的最終結(jié)果。箭頭函數(shù)用一個(gè)語(yǔ)句將隱式的返回結(jié)果(函數(shù)必須省略{},為了省略return關(guān)鍵詞)。
如果返回一個(gè)多行語(yǔ)句(比如對(duì)象),有必要在函數(shù)體內(nèi)使用()替代{}。這樣可以確保代碼是否作為一個(gè)單獨(dú)的語(yǔ)句返回。
function calcCircumference(diameter) {return Math.PI * diameter}//orcalcCircumference = diameter => (Math.PI * diameter;)
默認(rèn)參數(shù)值
你可以使用if語(yǔ)句來(lái)定義函數(shù)參數(shù)的默認(rèn)值。在ES6中,可以在函數(shù)聲明中定義默認(rèn)值。
function volume(l, w, h) {if (w === undefined) w = 3;if (h === undefined) h = 4;return l * w * h;}//orvolume = (l, w = 3, h = 4) => (l * w * h);volume(2); // 24
Template Literals(字符串模板)
是不是厭倦了使用+來(lái)連接多個(gè)變量變成一個(gè)字符串?難道就沒有一個(gè)更容易的方法嗎?如果你能使用ES6,那么你是幸運(yùn)的。在ES6中,你要做的是使用撇號(hào)和${},并且把你的變量放在大括號(hào)內(nèi)。
const welcome = ’You have logged in as’ + first + ’ ’ + last + ’.’;const db = ’http://’ + host + ’:’ + port + ’/’ + database;//orconst welcome = `You have logged in as ${first} ${last}`;const db = `http://${host}:${port}/${database}`;
Destructuring Assignment(解構(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;//orimport {observable, action, runInAction} from ’mobx’;const {store, form, loading, errors, entity} = this.props;
你甚至可以自己指定變量名:
const {store, form, loading, errors, entity:contact} = this.props; //通過 : 號(hào)來(lái)重命名
Spread Operator(擴(kuò)展運(yùn)算符)
Spread Operator是ES6中引入的,使JavaScript代碼更高效和有趣。它可以用來(lái)代替某些數(shù)組的功能。Spread Operator只是一個(gè)系列的三個(gè)點(diǎn)(...)。
// Joining arraysconst odd = [1, 3, 5];const nums = [2, 4, 6].concat(odd);// cloning arraysconst arr = [1, 2, 3, 4];const arr2 = arr.slice();//or// Joining arraysconst odd = [1, 3, 5];const nums = [2, 4, 6, ...odd];console.log(nums); // [2, 4, 6, 1, 3, 5]// cloning arraysconst arr = [1, 2, 3, 4];const arr2 = [...arr];
不像concat()函數(shù),使用Spread Operator你可以將一個(gè)數(shù)組插入到另一個(gè)數(shù)組的任何地方。
const odd = [1, 3, 5];const nums = [2, ...odd, 4, 6];
另外還可以當(dāng)作解構(gòu)符:
const {a, b, ...z} = {a: 1, b: 2, c: 3, d: 4};console.log(a); // 1console.log(b); // 2console.log(z); // {c: 3, d: 4}
強(qiáng)制參數(shù)
function foo(bar) {if (bar === undefined) {throw new Error(’Missing parameter!’); }return bar;}//ormandatory = () => {throw new Error(’Missing parameter!’);}foo = (bar = mandatory()) => {return bar;}
Array.find
如果你以前寫過一個(gè)查找函數(shù),你可能會(huì)使用一個(gè)for循環(huán)。在ES6中,你可以使用數(shù)組的一個(gè)新功能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]; } }} // orpet = pets.find(pet => pet.type === ’Dog’ && pet.name === ’Tommy’);console.log(pet); // {type: ’Dog’, name: ’Tommy’}
Object[key]
你知道Foo.bar也可以寫成Foo[bar]吧。起初,似乎沒有理由應(yīng)該這樣寫。然而,這個(gè)符號(hào)可以讓你編寫可重用代碼塊。
function validate(values) {if (!values.first)return false;if (!values.last)return false;return true;}console.log(validate({first: ’Bruce’, last: ’Wayne’})); // true
這個(gè)函數(shù)可以正常工作。然而,需要考慮一個(gè)這樣的場(chǎng)景:有很多種形式需要應(yīng)用驗(yàn)證,而且不同領(lǐng)域有不同規(guī)則。在運(yùn)行時(shí)很難創(chuàng)建一個(gè)通用的驗(yàn)證功能。
// object validation rulesconst schema = {first: {required: true },last: {required: true }}// universal validation functionconst validate = (schema, values) => {for(field in schema) {if (schema[field].required) {if(!values[field]) {return false; } } }return true;}console.log(validate(schema, {first: ’Bruce’})); // falseconsole.log(validate(schema, {first: ’Bruce’, last: ’Wayne’})); //true
現(xiàn)在我們有一個(gè)驗(yàn)證函數(shù),可以各種形式的重用,而不需要為每個(gè)不同的功能定制一個(gè)驗(yàn)證函數(shù)。
Double Bitwise NOT
如果你是一位JavaScript新手的話,對(duì)于逐位運(yùn)算符(Bitwise Operator)你應(yīng)該永遠(yuǎn)不會(huì)在任何地方使用。此外,如果你不處理二進(jìn)制0和1,那就更不會(huì)想使用。
然而,一個(gè)非常實(shí)用的用例,那就是雙位操作符。你可以用它替代Math.floor()。Double Bitwise NOT運(yùn)算符有很大的優(yōu)勢(shì),它執(zhí)行相同的操作要快得多。你可以在這里閱讀更多關(guān)于位運(yùn)算符相關(guān)的知識(shí)。
Math.floor(4.9) === 4; // true//or~~4.9 === 4; //true
以上就是JavaScript編碼小技巧分享的詳細(xì)內(nèi)容,更多關(guān)于JavaScript編碼技巧的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用Python webdriver圖書館搶座自動(dòng)預(yù)約的正確方法2. android H5本地緩存加載優(yōu)化的實(shí)戰(zhàn)3. 詳解如何使用Net將HTML簡(jiǎn)歷導(dǎo)出為PDF格式4. Python3 json模塊之編碼解碼方法講解5. 在線php代碼縮進(jìn)、代碼美化工具:PHP Formatter6. SpringBoot整合Redis的步驟7. PHP程序員簡(jiǎn)單的開展服務(wù)治理架構(gòu)操作詳解(二)8. 從Python的字符串中剝離所有非數(shù)字字符(“。”除外)9. PHP如何開啟Opcache功能提升程序處理效率10. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條

網(wǎng)公網(wǎng)安備