国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

8 個有用的JS技巧(推薦)

2024-05-06 15:37:11
字體:
來源:轉載
供稿:網友

為了保證的可讀性,本文采用意譯而非直譯。

想閱讀更多優質文章請猛戳GitHub博客,一年百來篇優質文章等著你!

這些技巧可能大家大部分都用過了,如果用過就當作加深點映像,如果沒有遇到過,就當作學會了幾個技巧。

1. 確保數組值

使用 grid ,需要重新創建原始數據,并且每行的列長度可能不匹配, 為了確保不匹配行之間的長度相等,可以使用Array.fill方法。

let array = Array(5).fill('');console.log(array); // outputs (5) ["", "", "", "", ""]

2. 獲取數組唯一值

ES6 提供了從數組中提取惟一值的兩種非常簡潔的方法。不幸的是,它們不能很好地處理非基本類型的數組。在本文中,主要關注基本數據類型。

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.使用展開運算符合并對象和對象數組

對象合并是很常見的事情,我們可以使用新的ES6特性來更好,更簡潔的處理合并的過程。

// merging objectsconst 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 oneconst 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);/* outputsBerlin: "no"Genoa: "yes"Hamburg: "yes"Lyon: "no"Marseille: "yes"Milan: "no"New York: "yes"Palermo: "yes"Paris: "no"Rome: "yes"*/

4. 數組 map 的方法 (不使用Array.Map)

另一種數組 map 的實現的方式,不用 Array.map。

Array.from 還可以接受第二個參數,作用類似于數組的map方法,用來對每個元素進行處理,將處理后的值放入返回的數組。如下:

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"]            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 同江市| 常宁市| 潞城市| 平舆县| 买车| 锦州市| 和田县| 隆尧县| 长治市| 布尔津县| 敖汉旗| 平谷区| 潼关县| 澄江县| 凤凰县| 钟祥市| 年辖:市辖区| 湛江市| 星子县| 稷山县| 高安市| 定襄县| 建昌县| 新龙县| 苏尼特右旗| 临漳县| 潜山县| 东方市| 宁南县| 贞丰县| 望谟县| 准格尔旗| 论坛| 苏尼特右旗| 昆山市| 锡林郭勒盟| 张家川| 新邵县| 伊通| 建阳市| 铁岭市|