国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術(shù)文章
文章詳情頁

JavaScript編碼小技巧分享

瀏覽:43日期:2023-10-13 11:19:07

三元操作符

如果使用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ǎn)冗長,特別是嵌套函數(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)使用()替代{}。這樣可以確保代碼是否作為一個單獨(dú)的語句返回。

function calcCircumference(diameter) {return Math.PI * diameter}//orcalcCircumference = diameter => (Math.PI * diameter;)

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

你可以使用if語句來定義函數(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(字符串模板)

是不是厭倦了使用+來連接多個變量變成一個字符串?難道就沒有一個更容易的方法嗎?如果你能使用ES6,那么你是幸運(yùn)的。在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(擴(kuò)展運(yùn)算符)

Spread Operator是ES6中引入的,使JavaScript代碼更高效和有趣。它可以用來代替某些數(shù)組的功能。Spread Operator只是一個系列的三個點(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你可以將一個數(shù)組插入到另一個數(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

如果你以前寫過一個查找函數(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)用驗(yàn)證,而且不同領(lǐng)域有不同規(guī)則。在運(yùn)行時很難創(chuàng)建一個通用的驗(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)在我們有一個驗(yàn)證函數(shù),可以各種形式的重用,而不需要為每個不同的功能定制一個驗(yàn)證函數(shù)。

Double Bitwise NOT

如果你是一位JavaScript新手的話,對于逐位運(yùn)算符(Bitwise Operator)你應(yīng)該永遠(yuǎn)不會在任何地方使用。此外,如果你不處理二進(jìn)制0和1,那就更不會想使用。

然而,一個非常實(shí)用的用例,那就是雙位操作符。你可以用它替代Math.floor()。Double Bitwise NOT運(yùn)算符有很大的優(yōu)勢,它執(zhí)行相同的操作要快得多。你可以在這里閱讀更多關(guān)于位運(yùn)算符相關(guān)的知識。

Math.floor(4.9) === 4; // true//or~~4.9 === 4; //true

以上就是JavaScript編碼小技巧分享的詳細(xì)內(nèi)容,更多關(guān)于JavaScript編碼技巧的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 最新国产毛片 | 免费区一级欧美毛片 | 欧美成人26uuu欧美毛片 | 99亚洲精品 | 一级毛片在线视频 | 久久久久久久99精品免费观看 | 国产20页 | 手机看片日韩日韩国产在线看 | 黄色毛片免费 | 免费黄色在线网址 | 欧美视频精品在线 | 色老头一区二区三区在线观看 | 久久国产精品久久久 | 手机在线国产精品 | 手机在线看片福利 | 欧美a大片欧美片 | 欧美成人影院免费观 | 久久99久久精品视频 | 日本韩国欧美一区 | 国产片一级aaa毛片视频 | 国产高清国产专区国产精品 | 一级真人毛片 | 中文字幕亚洲一区二区三区 | 99国产精品久久久久久久... | 久久精品全国免费观看国产 | 男人的天堂在线观看入口 | 久久国产精品歌舞团 | 曰本美女高清在线观看免费 | 成人精品一区久久久久 | 国产高清一区二区 | 亚洲天堂男人在线 | 免费国产一区二区三区 | 777色狠狠一区二区三区 | 综合色久 | 亚洲精品一区二区三区四区手机版 | 99在线精品视频在线观看 | 亚洲国语在线视频手机在线 | 看一级毛片 | 国产高中生粉嫩无套第一次 | 国产免费一区二区三区在线观看 | 欧美亚洲一区二区三区四 |