您可以轻松扩展它以拆分多个索引,并采用数组或字符串
const splitOn = (slicable, ...indices) =>
[0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));
splitOn('foo', 1);
// ["f", "oo"]
splitOn([1, 2, 3, 4], 2);
// [[1, 2], [3, 4]]
splitOn('fooBAr', 1, 4);
// ["f", "ooB", "Ar"]
lodash 问题跟踪器:https ://github.com/lodash/lodash/issues/3014
打字稿:
const splitOn: {
<T = string>(s: T, ...i: number[]): T[];
<T extends any[]>(s: T, ...i: number[]): T[];
} = <T>(slicable: string | T[], ...indices: number[]) =>
[0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));