Access every other item in an array - JavaScript

后端 未结 2 615
有刺的猬
有刺的猬 2021-01-05 08:44

Is it possible for me to access every other item in an array? So basically, all items in positions 0, 2, 4, 6 etc.

Here\'s my code if it helps:

funct         


        
2条回答
  •  被撕碎了的回忆
    2021-01-05 08:59

    You can use the index (second parameter) in the array filter method like this:

    let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    // filter out all elements that are located at an even index in the array.
    
    let x = arr.filter((element, index) => {
      return index % 2 === 0;
    })
    
    console.log(x) 
    // [1, 3, 5, 7, 9]
    

提交回复
热议问题