JavaScript編碼小技巧分享
三元操作符
如果使用if...else語句,那么這是一個很好節(jié)省代碼的方式。
const x = 20;let big;if (x > 10) {big = true;} else {big = false;}//這樣寫...const big = x > 10 ? true : false;
Short-circuit Evaluation
分配一個變量值到另一個變量的時候,你可能想要確保變量不是null、undefined或空。你可以寫一個有多個if的條件語句或者Short-circuit Evaluation。
if (variable1 !== null || variable1 !== undefined || variable1 !== ’’) { let variable2 = variable1;}// 這樣寫const variable2 = variable1 || ’new’;
不要相信我,請先相信自己的測試(可以把下面的代碼粘貼在es6console)
let variable1;let variable2 = variable1 || ’’;console.log(variable2 === ’’); // truevariable1 = ’foo’;variable2 = variable1 || ’’;console.log(variable2); // foo
聲明變量
在函數(shù)中聲明變量時,像下面這樣同時聲明多個變量可以節(jié)省你大量的時間和空間:
let x;let y;let x = 3;// or let x, y, z = 3;
如果存在
這可能是微不足道的,但值得提及。做“如果檢查”時,賦值操作符有時可以省略。
if (likeJavaScript === true)//orif (likeJavaScript)
注:這兩種方法并不完全相同,簡寫檢查只要likeJavaScript是true都將通過。
這有另一個示例。如果a不是true,然后做什么。
let a;if (a !== true) {// do something ...}//orlet a;if (!a) {// do something ...}
JavaScript的for循環(huán)
如果你只想要原生的JavaScript,而不想依賴于jQuery或Lodash這樣的外部庫,那這個小技巧是非常有用的。
for (let i = 0; i < allImgs.length; i++)//orfor (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
對象屬性
定義對象文字(Object literals)讓JavaScript變得更有趣。ES6提供了一個更簡單的辦法來分配對象的屬性。如果屬性名和值一樣,你可以使用下面簡寫的方式。
const obj = {x: x, y: y};//orconst obj = {x, y};
箭頭函數(shù)
經(jīng)典函數(shù)很容易讀和寫,但它們確實會變得有點冗長,特別是嵌套函數(shù)中調(diào)用其他函數(shù)時還會讓你感到困惑。
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)常使用到的一個關(guān)鍵詞,將返回函數(shù)的最終結(jié)果。箭頭函數(shù)用一個語句將隱式的返回結(jié)果(函數(shù)必須省略{},為了省略return關(guān)鍵詞)。
如果返回一個多行語句(比如對象),有必要在函數(shù)體內(nèi)使用()替代{}。這樣可以確保代碼是否作為一個單獨的語句返回。
function calcCircumference(diameter) {return Math.PI * diameter}//orcalcCircumference = diameter => (Math.PI * diameter;)
默認參數(shù)值
你可以使用if語句來定義函數(shù)參數(shù)的默認值。在ES6中,可以在函數(shù)聲明中定義默認值。
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(字符串模板)
是不是厭倦了使用+來連接多個變量變成一個字符串?難道就沒有一個更容易的方法嗎?如果你能使用ES6,那么你是幸運的。在ES6中,你要做的是使用撇號和${},并且把你的變量放在大括號內(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; //通過 : 號來重命名
Spread Operator(擴展運算符)
Spread Operator是ES6中引入的,使JavaScript代碼更高效和有趣。它可以用來代替某些數(shù)組的功能。Spread Operator只是一個系列的三個點(...)。
// 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你可以將一個數(shù)組插入到另一個數(shù)組的任何地方。
const odd = [1, 3, 5];const nums = [2, ...odd, 4, 6];
另外還可以當作解構(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}
強制參數(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
如果你以前寫過一個查找函數(shù),你可能會使用一個for循環(huán)。在ES6中,你可以使用數(shù)組的一個新功能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)該這樣寫。然而,這個符號可以讓你編寫可重用代碼塊。
function validate(values) {if (!values.first)return false;if (!values.last)return false;return true;}console.log(validate({first: ’Bruce’, last: ’Wayne’})); // true
這個函數(shù)可以正常工作。然而,需要考慮一個這樣的場景:有很多種形式需要應(yīng)用驗證,而且不同領(lǐng)域有不同規(guī)則。在運行時很難創(chuàng)建一個通用的驗證功能。
// 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)在我們有一個驗證函數(shù),可以各種形式的重用,而不需要為每個不同的功能定制一個驗證函數(shù)。
Double Bitwise NOT
如果你是一位JavaScript新手的話,對于逐位運算符(Bitwise Operator)你應(yīng)該永遠不會在任何地方使用。此外,如果你不處理二進制0和1,那就更不會想使用。
然而,一個非常實用的用例,那就是雙位操作符。你可以用它替代Math.floor()。Double Bitwise NOT運算符有很大的優(yōu)勢,它執(zhí)行相同的操作要快得多。你可以在這里閱讀更多關(guān)于位運算符相關(guān)的知識。
Math.floor(4.9) === 4; // true//or~~4.9 === 4; //true
以上就是JavaScript編碼小技巧分享的詳細內(nèi)容,更多關(guān)于JavaScript編碼技巧的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. IntelliJ IDEA刪除類的方法步驟2. js select支持手動輸入功能實現(xiàn)代碼3. PHP正則表達式函數(shù)preg_replace用法實例分析4. Django視圖類型總結(jié)5. vue使用moment如何將時間戳轉(zhuǎn)為標準日期時間格式6. Vue實現(xiàn)仿iPhone懸浮球的示例代碼7. Android 實現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進程8. JSP中Servlet的Request與Response的用法與區(qū)別9. Struts2獲取參數(shù)的三種方法總結(jié)10. vue cli4下環(huán)境變量和模式示例詳解
