“Array foreach dans JavaScript FSD” Réponses codées

Array foreach dans 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 dans 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

Réponses similaires à “Array foreach dans JavaScript FSD”

Questions similaires à “Array foreach dans JavaScript FSD”

Plus de réponses similaires à “Array foreach dans JavaScript FSD” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code