8个有用的JS技巧

原文 | https://devinduct.com/blogpost/26/8-useful-javascript-tricks

译文 | https://github.com/qq449245884/xiaozhi/issues/69

这些技巧可能大家大部分都用过了,如果用过就当作加深点映像,如果没有遇到过,就当作学会了几个技巧。

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"]

5. 有条件的对象属性

不再需要根据一个条件创建两个不同的对象,可以使用展开运算符号来处理。

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. 解构原始数据

有时候一个对象包含很多属性,而我们只需要其中的几个,这里可以使用解构方式来提取我们需要的属性。如一个用户对象内容如下:

const rawUser = { name: 'John', surname: 'Doe', email: 'john@doe.com', displayName: 'SuperCoolJohn', joined: '2016-05-05', image: 'path-to-the-image', followers: 45 ...}

我们需要提取出两个部分,分别是用户及用户信息,这时可以这样做:

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. 动态属性名

早期,如果属性名需要是动态的,我们首先必须声明一个对象,然后分配一个属性。这些日子已经过去了,有了ES6特性,我们可以做到这一点。

const dynamic = 'email';let user = { name: 'John', [dynamic]: 'john@doe.com'}console.log(user); // outputs { name: "John", email: "john@doe.com" }

8.字符串插值

在用例中,如果正在构建一个基于模板的helper组件,那么这一点就会非常突出,它使动态模板连接容易得多。

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.'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值