Which great god can have a solution
Your question
How to get the value in the array corresponding to the even-numbered subscript
In other words: Get the array
Based on the above sentence, it is a reasonable guess that what you are actually talking about is Get the arrays corresponding to even subscripts from the two-dimensional array and flatten them into an array
For example
var test = [
['a'],
['b'],
['c'],
['d']
]
After processing, the result is ['a', 'c']
, that is, the arrays corresponding to even subscripts are merged into one array
(the subscripts start from 0
0 is an even number
)
If you are convinced that this is the case, please continue reading
var isEven = i => i % 2 === 0;
var evens = arr => arr.filter(
// 子數(shù)組, 序號 => idx 是偶數(shù)則返回 true 否則 false
// 這樣可以過濾掉奇數(shù)下標的元素
(subArr, idx) => isEven(idx)
);
For example, [[1], [2]]
becomes [1, 2]
This process is paving
var flat = arr => arr.reduce((acc, cur) => {
// 每一次的返回值將會作為下一次的 acc 來用
// 那么每一次都把 acc cur 合并在一起 最后就是鋪平了
return acc.concat(cur)
}, [])
// 把 evens 執(zhí)行結(jié)果傳給 flat 執(zhí)行 作為 getAllEvens 的返回值
// 可以想象數(shù)學上的 y = g(f(x));
var getAllEvens = arr => {
let temp = evens(arr);
return flat(temp);
}
Define the array to be tested
// 二維數(shù)組
var testArr = [
['這里', '是', '0', '號', '數(shù)組', '當然是偶數(shù)'],
['所以', '這', '里', '是', '1號', '也就是奇數(shù)'],
[0,1,2,3,4],
[-1, -2, -3, -4]
];
The expected value is here is array number 0, which is of course an even number
and 0,1,2,3,4
The following is the test code:
var res = getAllEvens(testArr);
console.log('數(shù)組:', res);
console.log('合并:', res.join(','));
The result is as shown in the picture
Expected income, sure it’s feasible.
Some knowledge points
MDN - filter for arrays
MDN - reduce for arrays
MDN - arrow function
var array = [1,2,3,4];
for (var i=0;i<array.length;i++){
if (i%2==0) {
console.log(array[i]);
}
}
var array = [1,2,3,4];
var result = array.filter(function(index, value){
if (index%2==0) {
return true;
}
});
console(array);
console(result);
Help you simply implement a function
let arr = [0,1,2,3,4,5,6,7,8,9];
function even(arr){
return arr.filter((val,index)=>{
if(index%2 === 0){
return true;
}
})
};
even(arr);
//輸出[0, 2, 4, 6, 8]