首页 > 解决方案 > 返回新洗牌元素的索引

问题描述

这是我想要的:

我有first数组,我有index如下:

const first = ['a','b','c'];
const index = 1; // the index of b

const shuffled = ['c','a','b']; // now the index of b is 2 

first数组中index指向数组中的第二个元素是b正确的?

现在我打乱了first数组,我们有了shuffled数组。

的索引b现在是 2。我想返回这个新索引...

标签: javascript

解决方案


使用Array#indexOf

const first = ['a','b','c'];
const index = 1;
const shuffled = ['c','a','b'];

const target = first[index];
const newIndex = shuffled.indexOf(target);

console.log(newIndex);


推荐阅读