“Dapatkan setiap item lainnya dalam array” Kode Jawaban

JavaScript setiap elemen lain dalam array

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]
Khalon

Dapatkan setiap item lainnya dalam array

// If you want every even index value:
var myArray = ["First", "Second", "Third", "Fourth", "Fifth"]
function every_other(array){
    var temporaryArray = []
    for (var i = 1; i < array.length; i += 2){ //Add two to i every iteration
        temporaryArray.push(array[i]) //Add the element at index i to a temporary array
    }
    return temporaryArray.join(", ")
}
console.log(every_other(myArray)) //Expected output: Second, Fourth
Confused Chicken

Dapatkan setiap item lainnya dalam array

// If you want every odd index value:
var myArray = ["First", "Second", "Third", "Fourth", "Fifth"]
function every_other(array){
    var temporaryArray = []
    for (var i = 0; i < array.length; i += 2){ //Add two to i every iteration
        temporaryArray.push(array[i]) //Add the element at index i to a temporary array
    }
    return temporaryArray.join(", ")
}
console.log(every_other(myArray)) //Expected output: First, Third, Fifth
Confused Chicken

Jawaban yang mirip dengan “Dapatkan setiap item lainnya dalam array”

Pertanyaan yang mirip dengan “Dapatkan setiap item lainnya dalam array”

Lebih banyak jawaban terkait untuk “Dapatkan setiap item lainnya dalam array” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya