个人网站备案网站内容网络营销的优缺点
先认识一下Set
概念:存储唯一值的集合,元素只能是值,没有键与之对应。Set中的每个值都是唯一的。
特性:
值的集合,值可以是任何类型。
值的唯一性,每个值只能出现一次。
保持了插入顺序。
不支持通过索引来访问元素。
时间复杂度:
查找、插入、删除操作通常是O(1)。
适用场景:
- 去重
let string = "banana";
let uniqueChars = [...new Set(string)].join('');
console.log(uniqueChars);let arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr)// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- 存储不可重复的数据,如游戏中的玩家名单
const playerSet = new Set()playerSet.add('player1')
playerSet.add('player2')
playerSet.add('player3')// 尝试添加重复的元素,不会生效
playerSet.add('player1')console.log(playerSet)// Set(3) { 'player1', 'player2', 'player3' }console.log(playerSet.has('player2'))// trueplayerSet.delete('player2')
console.log(playerSet)// Set(2) { 'player1', 'player3' }
Set转换为数组的方法
- 扩展运算符(Spread Operator)
const mySet = new Set([1, 2, 3]);
const myArray = [...mySet];
console.log(myArray);// [ 1, 2, 3 ]
- Array.from()方法
const mySet = new Set([1, 2, 3]);
const myArray = Array.from(mySet);
console.log(myArray);// [ 1, 2, 3 ]
- Array.prototype.forEach()方法
const mySet = new Set([1, 2, 3]);
const myArray= [];
mySet.forEach((value) => myArray.push(value));
console.log(myArray);// [ 1, 2, 3 ]
推荐使用扩展运算符和Array.from()方法,最直观和简洁的选择。
Set转换为Object的方法
- 使用扩展运算符(Spread Operator)和Object.fromEntries()方法
const mySet = new Set([1, 2, 3]);
const myObject = Object.fromEntries([...mySet].map(value => [value, value]));
console.log(myObject);// { '1': 1, '2': 2, '3': 3 }
- reduce() 方法:
const mySet = new Set([1, 2, 3]);
const myObject = [...mySet].reduce((obj, value) => {obj[value] = value;return obj;
}, {});
console.log(myObject);// { '1': 1, '2': 2, '3': 3 }
- forEach() 方法:
const mySet = new Set([1, 2, 3]);
const myObject = {};
mySet.forEach(value => {myObject[value] = value;
});
console.log(myObject);// { '1': 1, '2': 2, '3': 3 }
扩展运算符(Spread Operator)和 Object.fromEntries() 方法简洁、直观,易于理解,是ES6中推荐的做法。
reduce() 方法倾向于函数式编程或者想要在单个步骤中完成转换。
对于简单的情况,forEach() 方法可能更易于理解和实现。
数组转换为Set的方法
Set构造函数
const myArray = [1, 2, 3];
const mySet = new Set(myArray);
console.log(mySet);// Set(3) { 1, 2, 3 }
使用Set构造函数即可。