“Tablica Foreach w JavaScript FSD” Kod odpowiedzi

Tablica Foreach w 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

Tablica Foreach w 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

Odpowiedzi podobne do “Tablica Foreach w JavaScript FSD”

Pytania podobne do “Tablica Foreach w JavaScript FSD”

Więcej pokrewnych odpowiedzi na “Tablica Foreach w JavaScript FSD” w JavaScript

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu