是否有单行代码通过索引从数组中获取子数组?
例如,假设我希望["a","c","e"]
从["a","b","c","d","e"]
获得[0,2,4]
。如何使用单行代码执行此操作?像["a","b","c","d","e"][0,2,4]
..
答案 0 :(得分:8)
您可以使用map
;
var array1 = ["a","b","c"];
var array2 = [0,2];
var array3 = array2.map(i => array1[i]);
console.log(array3);

答案 1 :(得分:3)
您可以使用Array#filter
和Array#includes
const array = ['a','b','c'];
console.log(array.filter((x,i) => [0,2].includes(i)));

答案 2 :(得分:3)
您可以使用filter
const arr = ['a', 'b', 'c'];
const indexes = [0, 2];
const result = arr.filter((elt, i) => indexes.indexOf(i) > -1);
document.body.innerHTML = result;

答案 3 :(得分:2)
您可以使用Array.prototype.reduce()
const arr = ['a', 'b', 'c', 'd', 'e'];
const indexes = [0, 2, 4];
const result = indexes.reduce((a, b)=> {
a.push(arr[b]);
return a;
}, []);
console.log(result);