我有两个数组。
我的数据之一:
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
最好的方法是什么?
答案 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的键和值将不匹配。