根据来自另一个表的索引获取数组的元素

时间:2019-12-06 00:14:47

标签: javascript jquery arrays

我有两个数组。
我的数据之一:

var tab1 = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"];

另一个是int的

var tab2 = [1,4,5,8,12,15,18];

我想放入tab3中的tab1个值,这些值具有从tab2的值开始的索引。
我曾尝试过一些indexOf // findIndexe
最好的方法是什么?

4 个答案:

答案 0 :(得分:2)

您可以将tab2数组映射到名为tab3的新数组

const tab1 = [
    "one","two","three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen",
    "fifteen","sixteen","seventeen","eighteen","nineteen","twenty"
];

const tab2 = [1,4,5,8,12,15,18];

const tab3 = tab2.map(index => tab1[index])
console.log(tab3)

问题要求索引。但是,如果所需的答案是数字的实际字符串表示形式,则可以在列表中搜索index-1项。

const tab1 = [
    "one","two","three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen",
    "fifteen","sixteen","seventeen","eighteen","nineteen","twenty"
];

const tab2 = [1,4,5,8,12,15,18];

const tab3 = tab2.map(index => tab1[index -1])
console.log(tab3)

答案 1 :(得分:2)

使用Array.map()

const tab1 = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"];

const tab2 = [1,4,5,8,12,15,18];

const tab3 = tab2.map(num => tab1[num - 1]);

console.log(tab3);

答案 2 :(得分:1)

让我们迭代包含索引的数组,然后将数据值与索引对应。

tab2.forEach(i => { 
    tab3.push(tab1[i]) 
})

答案 3 :(得分:0)

您可以通过使用对象来执行此操作,因为js中没有索引数组。

var tab1 = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty"];

var tab2 = [1,4,5,8,12,15,18];
var tab3 = {};
tab2.forEach((val) => {
    tab3[val] = tab1[val];
})

console.log(tab3);

当然,因为js数组从零开始,所以tab3的键和值将不匹配。