亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - How to get the value in the array corresponding to the even-numbered subscript
世界只因有你
世界只因有你 2017-07-05 10:49:24
0
4
2134

Which great god can have a solution

世界只因有你
世界只因有你

reply all(4)
阿神

Your question

How to get the value in the array corresponding to the even-numbered subscript

In other words: Get the array

corresponding to the even subscript in 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

First get the arrays corresponding to even subscripts

var isEven = i => i % 2 === 0; 

var evens = arr => arr.filter(
    // 子數(shù)組, 序號 => idx 是偶數(shù)則返回 true 否則 false 
    // 這樣可以過濾掉奇數(shù)下標的元素 
    (subArr, idx) => isEven(idx)
); 

Flatten the arrays obtained with evens

For example, [[1], [2]] becomes [1, 2]

after processing

This process is paving

var flat = arr => arr.reduce((acc, cur) => {
    // 每一次的返回值將會作為下一次的 acc 來用
    // 那么每一次都把 acc cur 合并在一起 最后就是鋪平了 
    return acc.concat(cur)
}, [])

Assembly

// 把 evens 執(zhí)行結(jié)果傳給 flat 執(zhí)行 作為 getAllEvens 的返回值 
// 可以想象數(shù)學上的 y = g(f(x)); 
var getAllEvens = arr => {
    let temp = evens(arr); 
    return flat(temp); 
}

Test

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(','));

ScreenShot

The result is as shown in the picture

Expected income, sure it’s feasible.

Links

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]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template