繁体   English   中英

Javascript:如何获取数组中特定顺序值的索引?

[英]Javascript: How do I get the index of a certain order of values in an array?

我目前正在尝试创建一个马尔可夫链。 现在,我需要获取数组中某些值的索引。 有没有可能的方法?

我尝试使用 indexOf,但它只支持一个参数。

假设有一个名为 INDEX 的 function 可以满足我的需要。

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 );

在这种情况下,一个非常简单和整洁的方法是处理字符串。

因此,您可以将 arrays 都转换为字符串并使用String.prototype.indexOf()

const INDEX = (arr, toFind) => arr.join('').indexOf(toFind.join(''))

 const arr = [1, 2, 3, 4, 3, 2, 3, 1] const INDEX = (arr, toFind) => arr.join('').indexOf(toFind.join('')) console.log( INDEX(arr, [1, 2]), INDEX(arr, [3, 4, 3]), INDEX(arr, [2, 3]), INDEX(arr, [5, 6]), INDEX(arr, [1, 4]) )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM