Access every other item in an array - JavaScript

后端 未结 2 614
有刺的猬
有刺的猬 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]
    
    0 讨论(0)
  • 2021-01-05 09:20

    If you just want this with lineLength and not with key, then add a second variable and use += when incrementing:

    function pushToHash(key, value) {
        for (var t = 0, x = 0; t < value.length; t++, x += 2) {
            MQHash[key[t]] = value.slice(0, lineLength[x]);
        }
    }
    

    (The power of the comma operator...)

    0 讨论(0)
提交回复
热议问题