我的博客主页:笔头博客
1、Array.includes
ES6提供,用于判断数组中是否包含指定值,返回 true/false
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
2、Set去重
ES6提供,它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构
const arr = [3, 5, 2, 2, 5, 5];
const unique = [...new Set(arr)];
// [3,5,2]
字符串去重
let str = [...new Set("ababbc")].join("");
console.log(str);
// 'abc'
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}
Set属性
Set.prototype.constructor:构造函数,默认就是Set函数。
Set.prototype.size:返回Set实例的成员总数。
add(value):添加某个值,返回 Set 结构本身。
delete(value):删除某个值,返回一个布尔值,表示删除是否成功。
has(value):返回一个布尔值,表示该值是否为Set的成员。
clear():清除所有成员,没有返回值。
Set遍历属性
keys():返回键名的遍历器
values():返回键值的遍历器
entries():返回键值对的遍历器
forEach():使用回调函数遍历每个成员
3、weakSet
WeakSet 结构与 Set 类似,也是不重复的值的集合。但是,它与 Set 有两个区别
首先,WeakSet 的成员只能是对象,而不能是其他类型的值
const ws = new WeakSet();
ws.add(1)
// TypeError: Invalid value used in weak set
ws.add(Symbol())
// TypeError: invalid value used in weak set
其次,WeakSet 中的对象都是弱引用,即垃圾回收机制不考虑 WeakSet 对该对象的引用,也就是说,如果其他对象都不再引用该对象,那么垃圾回收机制会自动回收该对象所占用的内存,不考虑该对象还存在于 WeakSet 之中
由于上面这个特点,WeakSet 的成员是不适合引用的,因为它会随时消失。另外,由于 WeakSet 内部有多少个成员,取决于垃圾回收机制有没有运行,运行前后很可能成员个数是不一样的,而垃圾回收机制何时运行是不可预测的,因此 ES6 规定 WeakSet 不可遍历。
4、Map
它类似于 Object 对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值,字符串、数值、布尔值、数组、对象等等都可以当作键。
const resultMap = new Map()
.set(-1, {text:'小于',color:'yellow')
.set(0, {text:'等于',color:'black')
.set(1, {text:'大于',color:'green')
.set(null,{text:'没有物品',color:'red'})
let state = resultMap.get(null)
// {text:'没有物品',color:'red'}
map还可以用于循环数组然后更改当前遍历项的值
const newArray = [{ a: 'b', c: 'd' }, { a: 'b', c: 'd' }];
newArray.map(item => {
item.b = 'e';
return item;
})
// [{"a":"b","c":"d","b":"e"},{"a":"b","c":"d","b":"e"}]
同样 map可以直接return dom节点
const newArray = [{ a: 'b', c: 'd' }, { a: 'b', c: 'd' }];
const dom = newArray.map(item => {
return <div>{item.a}</div>;
})
// 变量dom为dom节点
网友评论