如何从其他数组的数字位置获取数组?

时间:2021-03-20 06:59:50

标签: javascript

我有一个数组 A = [1,3] - 它存储来自另一个数组 B = ["answer1","answer2","answer3","answer4"] 的正确答案的位置。 我需要得到一个数组 C,它将由正确的答案组成,类似于 ["answer1","answer3"]

示例:如果数组 A 由 1 个元素组成(例如 A = [2]),则数组 C 应该类似于 C = ["answer2"]

当我有一个由 1 个元素组成的数组 A 时,我可以用 indexOf() 解决这个问题。但是当有 2 个或更多元素时,我会卡住

1 个答案:

答案 0 :(得分:5)

你应该这样做:

let A = [1,3];
let B = ["answer1","answer2","answer3","answer4"];
let C = A.map(i => B[i-1]);