根据另一个数组索引获取一个数组的值

时间:2016-06-24 17:50:46

标签: javascript arrays

我试图通过使用array2的索引来获取array1中的numierical值的值。所以例如我的数组看起来像这样:

const array1 = ["3","4","5","6","7","8"];
const array2 = ["bat","cat","dog","fish","cow","bird"];

如果用户选择"cat",则应抓取"4"

array2.forEach(animal => {
   console.log(array1.indexOf(animal)); // returns -1 
});

我该如何做到这一点?

3 个答案:

答案 0 :(得分:3)

将当前索引array2传递给forEach回调(第二个参数)



const array1 = ["3","4","5","6","7","8"];
const array2 = ["bat","cat","dog","fish","cow","bird"];

array2.forEach((animal, i) => {
   console.log(array1[i]);
});




答案 1 :(得分:3)

只需使用括号表示法和indexOf

const array1 = ["3","4","5","6","7","8"];
const array2 = ["bat","cat","dog","fish","cow","bird"];

let choice = 'cat'; // user selection

let result = array1[array2.indexOf(choice)]; // grab value

alert(result);

答案 2 :(得分:0)

您的代码需要进行一些更改。

据我所知,有两个条件。第一个是获取动物名称并在array1中搜索相关索引。第二个是你在array2上做一个循环,你得到array1中的相关项。

//First condition
var animalName = 'XXX'; // You get this from the user.
var indexOfAnimal = array2.indexOf(animalName); 
var relatedItem = array1[indexOfAnimal];

//Second condition
foreach(var index in array2){
    console.log(array1[index]);
}

//Your code with changes
array2.forEach(animal => {
    var indexOfAnimal = array2.indexOf(animal);
    console.log(array1[indexOfAnimal]);
});