Which great god can have a solution
阿神2017-07-05 10:51:24
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(
// 子数组, 序号 => idx 是偶数则返回 true 否则 false
// 这样可以过滤掉奇数下标的元素
(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 执行结果传给 flat 执行 作为 getAllEvens 的返回值
// 可以想象数学上的 y = g(f(x));
var getAllEvens = arr => {
let temp = evens(arr);
return flat(temp);
}
Define the array to be tested
// 二维数组
var testArr = [
['这里', '是', '0', '号', '数组', '当然是偶数'],
['所以', '这', '里', '是', '1号', '也就是奇数'],
[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('数组:', 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
大家讲道理2017-07-05 10:51:24
var array = [1,2,3,4];
for (var i=0;i<array.length;i++){
if (i%2==0) {
console.log(array[i]);
}
}
PHP中文网2017-07-05 10:51:24
var array = [1,2,3,4];
var result = array.filter(function(index, value){
if (index%2==0) {
return true;
}
});
console(array);
console(result);
为情所困2017-07-05 10:51:24
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]