新聞中心
你可能錯(cuò)過(guò)這些非常有用的技巧。

創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),沂源企業(yè)網(wǎng)站建設(shè),沂源品牌網(wǎng)站建設(shè),網(wǎng)站定制,沂源網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷,網(wǎng)絡(luò)優(yōu)化,沂源網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
翻譯自 10 Super Useful Tricks for JavaScript Developers,作者 Mahdhi Rezvi。
我們知道,JavaScript 這門語(yǔ)言正在高速發(fā)展中。伴隨著 ES2020,又有很多很棒的功能加入。老實(shí)說(shuō),您可以通過(guò)許多不同的方式編寫代碼。實(shí)現(xiàn)同樣一個(gè)功能,有的代碼很長(zhǎng)而有的卻很短。你可以通過(guò)一些小技巧來(lái)讓你的代碼更干凈清晰。下面這些小技巧肯定對(duì)你接下來(lái)的開發(fā)工作有所用處。
函數(shù)參數(shù)驗(yàn)證器
JavaScript 允許你對(duì)函數(shù)參數(shù)設(shè)置默認(rèn)值。通過(guò)這個(gè)特性,我們可以實(shí)現(xiàn)一個(gè)小技巧來(lái)驗(yàn)證函數(shù)參數(shù)。
- const isRequired = () => { throw new Error('param is required'); };
- const print = (num = isRequired()) => { console.log(`printing ${num}`) };
- print(2); //printing 2
- print(); // error
- print(null); //printing null
格式化 JSON 代碼
你肯定對(duì) JSON.stringify 非常熟悉了,但是你知道嗎,你也可以通過(guò) stringify 方法格式化你的代碼。其實(shí)這很簡(jiǎn)單。
stringify 方法有三個(gè)參數(shù),分別是 value replacer 和 space。后面兩個(gè)參數(shù)是可選的,所以我們平常也不會(huì)用到它們。想要縮進(jìn)輸出的代碼,我們可以使用2個(gè)空格 ,或者4個(gè)空格。
- console.log(JSON.stringify({ name:"John", Age:23 }, null, ' '));
- >>>
- {
- "name": "John",
- "Age": 23
- }
對(duì)數(shù)組去重
以往對(duì)數(shù)組去重我們會(huì)使用 filter 函數(shù)來(lái)過(guò)濾掉重復(fù)的值。但是現(xiàn)在我們可以使用新的 Set 特性來(lái)過(guò)濾。非常簡(jiǎn)單:
- let uniqueArray = [...new Set([1, 2, 3, 3, 3, "school", "school", 'ball', false, false, true, true])];
- >>> [1, 2, 3, "school", "ball", false, true]
去除數(shù)組中的 Boolean(v) 為 false 的值
有時(shí)候你想刪除數(shù)組中 Boolean(v) 為 false 的值。在 JavaScript 中只有以下 6 種:
- undefined
- null
- NaN
- 0
- 空字符串
- false
去除這些值最簡(jiǎn)單的辦法是使用下面的方法:
- array.filter(Boolean)
如果你想先做一些更改然后再過(guò)濾,你可以用下面的方法。要記住,原始數(shù)組 array 是一直沒(méi)變的,返回的是一個(gè)新數(shù)組。
- array
- .map(item => {
- // Do your changes and return the new item
- })
- .filter(Boolean);
同時(shí)合并多個(gè)對(duì)象
如果需要同時(shí)合并多個(gè)對(duì)象或者類,可以用下面這種方法。
- const user = {
- name: "John Ludwig",
- gender: "Male",
- };
- const college = {
- primary: "Mani Primary School",
- secondary: "Lass Secondary School",
- };
- const skills = {
- programming: "Extreme",
- swimming: "Average",
- sleeping: "Pro",
- };
- const summary = { ...user, ...college, ...skills };
- >>>
- {
- name: 'John Ludwig',
- gender: 'Male',
- primary: 'Mani Primary School',
- secondary: 'Lass Secondary School',
- programming: 'Extreme',
- swimming: 'Average',
- sleeping: 'Pro'
- }
三個(gè)點(diǎn)也叫擴(kuò)展操作符。
對(duì)數(shù)字?jǐn)?shù)組排序
JavaScript 數(shù)組有一個(gè)原生的排序方法 arr.sort。 這個(gè)排序方法默認(rèn)把數(shù)組元素轉(zhuǎn)換成字符串,并對(duì)其進(jìn)行字典序排序。這個(gè)默認(rèn)行為會(huì)在排序數(shù)字?jǐn)?shù)組時(shí)出現(xiàn)問(wèn)題,所以下面有一個(gè)辦法來(lái)處理這個(gè)問(wèn)題。
- [0, 10, 4, 9, 123, 54, 1].sort()
- >>> [0, 1, 10, 123, 4, 54, 9]
- [0, 10, 4, 9, 123, 54, 1].sort((a,b) => a-b);
- >>> [0, 1, 4, 9, 10, 54, 123]
禁用右鍵
有時(shí)候你可能想要禁止用戶點(diǎn)擊右鍵。雖然這個(gè)需求很少見,但是可能派的上用場(chǎng)。
這個(gè)簡(jiǎn)單的代碼片段就可以禁止用戶點(diǎn)擊右鍵了。
解構(gòu)時(shí)重命名
解構(gòu)賦值是 JavaScript 的一個(gè)特性,它允許直接從數(shù)組或者對(duì)象中獲取值,而不需要繁瑣的聲明變量再賦值。對(duì)對(duì)象來(lái)講,我們可以通過(guò)下面這種方式來(lái)給屬性名重新定義一個(gè)名字。
- const object = { number: 10 };
- // Grabbing number
- const { number } = object;
- // Grabbing number and renaming it as otherNumber
- const { number: otherNumber } = object;
- console.log(otherNumber); // 10
獲取數(shù)組中的最后一項(xiàng)
如果你想獲取數(shù)組中的最后一項(xiàng),你可以使用 slice 函數(shù),同時(shí)帶上一個(gè)負(fù)數(shù)作為參數(shù)。
- let array = [0, 1, 2, 3, 4, 5, 6, 7]
- console.log(array.slice(-1));
- >>>[7]
- console.log(array.slice(-2));
- >>>[6, 7]
- console.log(array.slice(-3));
- >>>[5, 6, 7]
等待 Promises 全部執(zhí)行完成
有時(shí)候你可能需要等待幾個(gè) promise 都執(zhí)行完然后進(jìn)行后面的操作。你可以使用 Promise.all 來(lái)并行執(zhí)行這些 promise。
- const PromiseArray = [
- Promise.resolve(100),
- Promise.reject(null),
- Promise.resolve("Data release"),
- Promise.reject(new Error('Something went wrong'))];
- Promise.all(PromiseArray)
- .then(data => console.log('all resolved! here are the resolve values:', data))
- .catch(err => console.log('got rejected! reason:', err))
要注意,只要 Promise.all 中有一個(gè)是 rejected 狀態(tài)時(shí),其會(huì)立即停止執(zhí)行并拋出異常。
如果你想忽略 resolved 或者 rejected 狀態(tài),你可以使用 Promise.allSettled。這個(gè)是 ES2020 的一個(gè)新特性。
- const PromiseArray = [
- Promise.resolve(100),
- Promise.reject(null),
- Promise.resolve("Data release"),
- Promise.reject(new Error("Something went wrong")),
- ];
- Promise.allSettled(PromiseArray)
- .then((res) => {
- console.log("here", res);
- })
- .catch((err) => console.log(err));
- >>>
- here [
- { status: 'fulfilled', value: 100 },
- { status: 'rejected', reason: null },
- { status: 'fulfilled', value: 'Data release' },
- {
- status: 'rejected',
- reason: Error: Something went wrong
- at Object.
- at Module._compile (internal/modules/cjs/loader.js:1200:30)
- at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
- at Module.load (internal/modules/cjs/loader.js:1049:32)
- at Function.Module._load (internal/modules/cjs/loader.js:937:14)
- at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
- at internal/main/run_main_module.js:17:4
分享文章:對(duì)JavaScript開發(fā)者非常有用的10個(gè)技巧
文章轉(zhuǎn)載:http://m.fisionsoft.com.cn/article/dhgjjgg.html


咨詢
建站咨詢
