1.字符串快速转数字类型的
let str = '1'let str2 = +strconsole.log(typeof str2) // number
2.数字快速转字符串类型
let num = 1let str = '' + numconsole.log(typeof str) // string
3.二维数组转对象
const objects = [{ key1: 'value1' }, { key2: 'value2' }];const obj = Object.assign({}, ...objects);console.log(obj); // { key1: 'value1', key2: 'value2' }
const entries = [['key1', 'value1'], ['key2', 'value2']];const obj = Object.fromEntries(entries);console.log(obj); // { key1: 'value1', key2: 'value2' }
4.对象转数组
const obj = { a: 1, b: 2, c: 3 };const valuesArray = [...Object.values(obj)];const keysArray = [...Object.keys(obj)];const entriesArray = [...Object.entries(obj)];console.log(valuesArray); // [1, 2, 3]console.log(keysArray); // ['a', 'b', 'c']console.log(entriesArray); // [['a', 1], ['b', 2], ['c', 3]]
5.快速扁平化多维数组
const arr = [1,2,[3,4],[5,[6,7]]]const arr1 = arr.flat()const arr2 = arr.flat(2)console.log(arr1) // [1,2,3,4,5,[6,7]]console.log(arr2) // [1,2,3,4,5,6,7]
6.flatmap,map和flat的结合
const arr = [1,2,3,4,5]const arr1 = arr.flatMap(item=>item*2)console.log(arr1) //[2,4,6,8,10] 如果是只是用map的话,那么输出的结果就是[[2],[4],[6],[8],[10]]
7.使用解构赋值快速交换两个变量的值
let a = 1, b = 2;[a, b] = [b, a]; // 交换a和b的值
8.使用set结构快速去重
const arr = [1, 2, 2, 3, 4, 5, 5, 3];const uniqueArr = [...new Set(arr)];console.log(uniqueArr);
9.使用set实现并集、交集、差集
let a = new Set([1, 2, 3]);let b = new Set([4, 3, 2]);
// 并集let union = new Set([...a, ...b]);console.log(union); // Set {1, 2, 3, 4}
// 交集let intersect = new Set([...a].filter(x => b.has(x)));console.log(intersect); // set {2, 3}
// 差集let difference = new Set([...a].filter(x => !b.has(x)));console.log(difference); // Set {1}
10.对于只赋值一次的数据,可以使用Object.freeze()方法来冻结,冻结后不可修改,但是可以提高效率
const obj = { a: 1, b: 2 };Object.freeze(obj);obj.a = 3console.log(obj); //{a: 1, b: 2}
创作不易,大家点点关注,下期再见
领取专属 10元无门槛券
私享最新 技术干货