javascript - Javascript:如何获取数组中特定顺序值的索引?
问题描述
我目前正在尝试创建一个马尔可夫链。现在,我需要获取数组中某些值的索引。有没有可能的方法?
我尝试使用 indexOf,但它只支持一个参数。
假设有一个名为 INDEX 的函数可以满足我的需要。
const arr = [1, 2, 3, 4, 3, 2, 3, 1];
INDEX(arr, [1, 2]) // returns 0, because 1, 2 is in the first index in the array.
INDEX(arr, [3, 4, 3]) // returns 2, because 3, 4, 3 starts at the third index.
INDEX(arr, [2, 3]) // returns 1, because there are two 2, 3s, so it returns the first.
INDEX(arr, [5, 6]) // returns -1, because it is not in the array.
INDEX(arr, [1, 4]) // even though these values are in the array, they aren't in the order, so returns -1
解决方案
使用.findIndex
, 并检查every
数组项之一是否跟随当前索引:
const arr = [1, 2, 3, 4, 3, 2, 3, 1];
const INDEX = (arr, toFind) => arr.findIndex(
(_, baseI, arr) => toFind.every((item, i) => arr[baseI + i] === item)
);
console.log(
INDEX(arr, [1, 2]), // returns 0, because 1, 2 is in the first index in the array.
INDEX(arr, [3, 4, 3]), // returns 2, because 3, 4, 3 starts at the third index.
INDEX(arr, [2, 3]), // returns 1, because there are two 2, 3s, so it returns the first.
INDEX(arr, [5, 6]), // returns -1, because it is not in the array.
INDEX(arr, [1, 4]) // even though these values are in the array, they aren't in the order, so returns -1
);
推荐阅读
- javascript - 阿贾克斯 | jQuery | 成功块未调用 | AEM
- python - 如何在 Pandas 中将 varchar 转换为 int/float
- unity3d - Flutter 上的 Vuforia 说“引擎初始化错误”
- python - Python 3 - 使用 MySQL 连接器时光标上的弱引用错误
- javascript - 错误:元素类型无效:需要库的字符串:react-jsonschema-form
- python - 将 django-import-export 包添加到 Django 项目时运行服务器失败
- javascript - 导出的函数是否保证实例化一次?
- python - 无法打开端口 /dev/rfcomm0:[Errno 16] 设备或资源忙:'/dev/rfcomm0'
- aws-cdk - AWS CDK:如何将指定版本的 Lambda 与别名关联?
- nutch - 被nutch转储后的文件是什么编码?