Ric*_*cha 7 javascript typescript
我有以下代码摘录:
private getNextFakeLinePosition(startPosition: number): number{
return this.models.findIndex(m => m.fakeObject);
}
Run Code Online (Sandbox Code Playgroud)
此函数返回具有fakeObject真值属性的第一个元素的索引。
我想要的是这样的东西,但不是寻找数组的所有项目,我想从一个特定的位置 ( startPosition) 开始。
注意:这是打字稿,但解决方案可能是在 javascript vanilla 中。
谢谢你。
Rob*_*sen 12
回调findIndex()接收当前索引,因此您可以这样添加一个条件:
private getNextFakeLinePosition(startPosition: number): number {
return this.models.findIndex((m, i) => i >= startPosition && m.fakeObject);
}
Run Code Online (Sandbox Code Playgroud)
这不是最有效的解决方案,但只要您的数组不是太大,就应该可以。
您可以尝试使用slice:
private getNextFakeLinePosition(startPosition: number): number {
const index = this.models.slice(startPosition).findIndex(m => m.fakeObject);
return index === -1 ? -1 : index + startPosition;
}
Run Code Online (Sandbox Code Playgroud)
它将对您的输入数组进行切片并查找子数组上的索引。然后 - 最后,只需添加 即可startPosition获得真正的索引。
小智 5
在这种情况下我可能会使用for循环。它不会增加切片数组的开销,并避免不必要的索引检查。
const findStartFromPos = <T>(predicate: (e: T) => boolean, array: T[], startFrom: number): number => {
for (let i = startFrom; i < array.length; i++) {
if (predicate(array[i])) {
return i;
}
}
return -1;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1733 次 |
| 最近记录: |