此文章由jsjiami.com技术提供,需要js加解密可直接官网底部联系方式。
一、数组相关
1、数值类型转数组
- JS版本
const castArray = (value) => (Array.isArray(value) ? value : [value]);
castArray(1); // [1]
- TS版本
const castArray = <T,_>(value: T | T[]): T[] => (Array.isArray(value) ? value : [value]);
castArray(1); // [1]
2、校验数组是否为空
- JS版本
const isEmpty = (arr) => Array.isArray(arr) && !arr.length;
isEmpty([]); // true
- TS版本
const isEmpty = <T,_>(arr: T[]): boolean => Array.isArray(arr) && !arr.length;
isEmpty([1, 2, 3]); // false
3、将对象数组转为单个对象
- JS版本
const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});
//Or
const toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));
- TS版本
const toObject = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T> => (
arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {})
);
// Or
const toObject = <T extends Record<string, any>, K extends keyof T>(arr: T[], key: K): Record<string, T> => (
Object.fromEntries(arr.map((it) => [it[key], it]))
);
- 示例
toObject(
[
{ id: '1', name: 'Alpha', gender: 'Male' },
{ id: '2', name: 'Bravo', gender: 'Male' },
{ id: '3', name: 'Charlie', gender: 'Female' },
],
'id'
);
/*
{
'1': { id: '1', name: 'Alpha', gender: 'Male' },
'2': { id: '2', name: 'Bravo', gender: 'Male' },
'3': { id: '3', name: 'Charlie', gender: 'Female' },
}
*/
4、两个数组比较
- JS版本
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
//Or
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
isEqual([1, 2, 3], [1, 2, 3]); // true
- TS版本
const isEqual = <T,_>(a: T[], b: T[]): boolean => JSON.stringify(a) === JSON.stringify(b);标签:arr,const,解密,value,JS,key,isEqual,要会,id From: https://blog.51cto.com/u_15781271/6044924
//Or
const isEqual = <T,_>(a: T[], b: T[]): boolean => a.length === b.length && a.every((v, i) => v === b[i]);
isEqual([1, 2, 3], [1, '2', 3]); // false