https://mp.weixin.qq.com/s/woTlF_rvtqtySK0-BXhkUA
1. 确保数组有值
let array = Array(5).fill('');
console.log(array); // outputs (5) ["", "", "", "", ""]
2.获取数组唯一值(去重)
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.使用扩展运算符合并对象和对象数组
4.数组映射 (不使用 Array. 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"]
这里 Array.from:Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。
所谓类数组对象,最基本的要求就是具有length属性的对象。
Array.from(arrayLike, mapFn, thisArg)
arrayLike
想要转换成数组的伪数组对象或可迭代对象。
mapFn (可选参数)
如果指定了该参数,新数组中的每个元素会执行该回调函数。
thisArg (可选参数)
可选参数,执行回调函数 mapFn 时 this 对象。
5.带条件的对象属性
有时需要根据一个条件判断让对象包含特定的属性,实现这点不再需要创建两个不同的对象。为了达到这个目的,使用扩展运算符再合适不过。
6.解构原始数据
您是否曾经遇到过包含太多数据的对象?很确信你有过这样的经历。最常见的情况可能就是用一个用户对象包含了所有详细信息的数据。在这里,我们可以调用新的 ES 解构特性来挽救这种情形。让我们用一个例子来支持这个观点。
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“组件。这使得字符实现动态模板连接成为举手之劳。
使用模板字符串ES6新增