首页 > 语言 > 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"]            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选