“Array Foreach di JavaScript FSD” Kode Jawaban

Array Foreach di JavaScript FSD


Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1); // 2nd parameter means remove one item only
}

// array = [2, 9]
console.log(array); 
shafeeque

Array Foreach di JavaScript FSD

Your best bets are usually

a for-of loop (ES2015+ only; spec | MDN) - simple and async-friendly
for (const element of theArray) {
    // ...use `element`...
}
forEach (ES5+ only; spec | MDN) (or its relatives some and such) - not async-friendly (but see details)
theArray.forEach(element => {
    // ...use `element`...
});
a simple old-fashioned for loop - async-friendly
for (let index = 0; index < theArray.length; ++index) {
    const element = theArray[index];
    // ...use `element`...
}
(rarely) for-in with safeguards - async-friendly
for (const propertyName in theArray) {
    if (/*...is an array element property (see below)...*/) {
        const element = theArray[propertyName];
        // ...use `element`...
    }
}
shafeeque

Jawaban yang mirip dengan “Array Foreach di JavaScript FSD”

Pertanyaan yang mirip dengan “Array Foreach di JavaScript FSD”

Lebih banyak jawaban terkait untuk “Array Foreach di JavaScript FSD” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya