8 個(gè)有用的JS技巧(推薦)
為了保證的可讀性,本文采用意譯而非直譯。
想閱讀更多優(yōu)質(zhì)文章請(qǐng)猛戳GitHub博客,一年百來(lái)篇優(yōu)質(zhì)文章等著你!
這些技巧可能大家大部分都用過(guò)了,如果用過(guò)就當(dāng)作加深點(diǎn)映像,如果沒(méi)有遇到過(guò),就當(dāng)作學(xué)會(huì)了幾個(gè)技巧。
1. 確保數(shù)組值
使用 grid ,需要重新創(chuàng)建原始數(shù)據(jù),并且每行的列長(zhǎng)度可能不匹配, 為了確保不匹配行之間的長(zhǎng)度相等,可以使用Array.fill方法。
let array = Array(5).fill('');
console.log(array); // outputs (5) ["", "", "", "", ""]
2. 獲取數(shù)組唯一值
ES6 提供了從數(shù)組中提取惟一值的兩種非常簡(jiǎn)潔的方法。不幸的是,它們不能很好地處理非基本類(lèi)型的數(shù)組。在本文中,主要關(guān)注基本數(shù)據(jù)類(lèi)型。
const cars = [ 'Mazda', 'Ford', 'Renault', 'Opel', 'Mazda' ] const uniqueWithArrayFrom = Array.from(new Set(cars)); console.log(uniqueWithArrayFrom); // outputs ["Mazda", "Ford", "Renault", "Opel"] const uniqueWithSpreadOperator = [...new Set(cars)]; console.log(uniqueWithSpreadOperator);// outputs ["Mazda", "Ford", "Renault", "Opel"]
3.使用展開(kāi)運(yùn)算符合并對(duì)象和對(duì)象數(shù)組
對(duì)象合并是很常見(jiàn)的事情,我們可以使用新的ES6特性來(lái)更好,更簡(jiǎn)潔的處理合并的過(guò)程。
// merging objects
const product = { name: 'Milk', packaging: 'Plastic', price: '5$' }
const manufacturer = { name: 'Company Name', address: 'The Company Address' }
const productManufacturer = { ...product, ...manufacturer };
console.log(productManufacturer);
// outputs { name: "Company Name", packaging: "Plastic", price: "5$", address: "The Company Address" }
// merging an array of objects into one
const cities = [
{ name: 'Paris', visited: 'no' },
{ name: 'Lyon', visited: 'no' },
{ name: 'Marseille', visited: 'yes' },
{ name: 'Rome', visited: 'yes' },
{ name: 'Milan', visited: 'no' },
{ name: 'Palermo', visited: 'yes' },
{ name: 'Genoa', visited: 'yes' },
{ name: 'Berlin', visited: 'no' },
{ name: 'Hamburg', visited: 'yes' },
{ name: 'New York', visited: 'yes' }
];
const result = cities.reduce((accumulator, item) => {
return {
...accumulator,
[item.name]: item.visited
}
}, {});
console.log(result);
/* outputs
Berlin: "no"
Genoa: "yes"
Hamburg: "yes"
Lyon: "no"
Marseille: "yes"
Milan: "no"
New York: "yes"
Palermo: "yes"
Paris: "no"
Rome: "yes"
*/
4. 數(shù)組 map 的方法 (不使用Array.Map)
另一種數(shù)組 map 的實(shí)現(xiàn)的方式,不用 Array.map。
Array.from 還可以接受第二個(gè)參數(shù),作用類(lèi)似于數(shù)組的map方法,用來(lái)對(duì)每個(gè)元素進(jìn)行處理,將處理后的值放入返回的數(shù)組。如下:
const cities = [
{ name: 'Paris', visited: 'no' },
{ name: 'Lyon', visited: 'no' },
{ name: 'Marseille', visited: 'yes' },
{ name: 'Rome', visited: 'yes' },
{ name: 'Milan', visited: 'no' },
{ name: 'Palermo', visited: 'yes' },
{ name: 'Genoa', visited: 'yes' },
{ name: 'Berlin', visited: 'no' },
{ name: 'Hamburg', visited: 'yes' },
{ name: 'New York', visited: 'yes' }
];
const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
// outputs ["Paris", "Lyon", "Marseille", "Rome", "Milan", "Palermo", "Genoa", "Berlin", "Hamburg", "New York"]
5. 有條件的對(duì)象屬性
不再需要根據(jù)一個(gè)條件創(chuàng)建兩個(gè)不同的對(duì)象,可以使用展開(kāi)運(yùn)算符號(hào)來(lái)處理。
nst getUser = (emailIncluded) => {
return {
name: 'John',
surname: 'Doe',
...emailIncluded && { email : 'john@doe.com' }
}
}
const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }
const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }
6. 解構(gòu)原始數(shù)據(jù)
有時(shí)候一個(gè)對(duì)象包含很多屬性,而我們只需要其中的幾個(gè),這里可以使用解構(gòu)方式來(lái)提取我們需要的屬性。如一個(gè)用戶(hù)對(duì)象內(nèi)容如下:
const rawUser = {
name: 'John',
surname: 'Doe',
email: 'john@doe.com',
displayName: 'SuperCoolJohn',
joined: '2016-05-05',
image: 'path-to-the-image',
followers: 45
...
}
我們需要提取出兩個(gè)部分,分別是用戶(hù)及用戶(hù)信息,這時(shí)可以這樣做:
let user = {}, userDetails = {};
({ name: user.name, surname: user.surname, ...userDetails } = rawUser);
console.log(user); // outputs { name: "John", surname: "Doe" }
console.log(userDetails); // outputs { email: "john@doe.com", displayName: "SuperCoolJohn", joined: "2016-05-05", image: "path-to-the-image", followers: 45 }
7. 動(dòng)態(tài)屬性名
早期,如果屬性名需要是動(dòng)態(tài)的,我們首先必須聲明一個(gè)對(duì)象,然后分配一個(gè)屬性。這些日子已經(jīng)過(guò)去了,有了ES6特性,我們可以做到這一點(diǎn)。
const dynamic = 'email';
let user = {
name: 'John',
[dynamic]: 'john@doe.com'
}
console.log(user); // outputs { name: "John", email: "john@doe.com" }
8.字符串插值
在用例中,如果正在構(gòu)建一個(gè)基于模板的helper組件,那么這一點(diǎn)就會(huì)非常突出,它使動(dòng)態(tài)模板連接容易得多。
const user = {
name: 'John',
surname: 'Doe',
details: {
email: 'john@doe.com',
displayName: 'SuperCoolJohn',
joined: '2016-05-05',
image: 'path-to-the-image',
followers: 45
}
}
const printUserInfo = (user) => {
const text = `The user is ${user.name} ${user.surname}. Email: ${user.details.email}. Display Name: ${user.details.displayName}. ${user.name} has ${user.details.followers} followers.`
console.log(text);
}
printUserInfo(user);
// outputs 'The user is John Doe. Email: john@doe.com. Display Name: SuperCoolJohn. John has 45 followers.'
譯者:前端小智
原文:https://devinduct.com/blogpost/26/8-useful-javascript-tricks
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
element-ui 圖片壓縮上傳功能實(shí)現(xiàn)
這篇文章主要介紹了element-ui 圖片壓縮上傳功能實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-10-10
實(shí)用的js 焦點(diǎn)圖切換效果 結(jié)構(gòu)行為相分離
行為層是由js來(lái)實(shí)現(xiàn)的,這里的工作只是搭建了一個(gè)簡(jiǎn)單的骨架,如果要讓效果圖美觀些并符合設(shè)計(jì)要求,就要發(fā)揮css的強(qiáng)大作用了。2010-06-06
ASP中進(jìn)行HTML數(shù)據(jù)及JS數(shù)據(jù)編碼函數(shù)
在有些時(shí)候我們無(wú)法控制亂碼的出現(xiàn), 比如發(fā)送郵件的時(shí)候有些郵件顯示亂碼, 比如Ajax返回?cái)?shù)據(jù)總是亂碼. 怎么辦?2009-11-11
詳解微信小程序input標(biāo)簽正則初體驗(yàn)
這篇文章主要介紹了詳解微信小程序input標(biāo)簽正則初體驗(yàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
Javascript 遍歷對(duì)象中的子對(duì)象
昨天同事問(wèn)我一個(gè)問(wèn)題:“有一個(gè)JSON對(duì)象,其中有若干個(gè)子對(duì)象,如何遍歷這個(gè)對(duì)象中的子對(duì)象?”2009-07-07
JS實(shí)現(xiàn)模擬風(fēng)力的雪花飄落效果
這篇文章主要介紹了JS實(shí)現(xiàn)模擬風(fēng)力的雪花飄落效果,可在右側(cè)填入風(fēng)力值點(diǎn)擊按鈕即可看到伴隨風(fēng)力的雪花飄落效果,同時(shí)右側(cè)有實(shí)時(shí)雪花數(shù)量統(tǒng)計(jì)功能,需要的朋友可以參考下2015-05-05
Chart.js 輕量級(jí)HTML5圖表繪制工具庫(kù)(知識(shí)整理)
這篇文章主要介紹了Chart.js 輕量級(jí)HTML5圖表繪制工具庫(kù),Chart.js基于HTML5 canvas技術(shù)支持所有現(xiàn)代瀏覽器,并且針對(duì)IE7/8提供了降級(jí)替代方案,感興趣的小伙伴們可以參考一下2018-05-05

