Šajā piemērā jūs iemācīsities rakstīt JavaScript programmu, kas no masīva noņems konkrētu vienumu.
Lai saprastu šo piemēru, jums jāpārzina šādas JavaScript programmēšanas tēmas:
- JavaScript masīva push ()
- JavaScript masīva savienojums ()
- JavaScript ciklam
1. piemērs: Izmantojot cilnei
// program to remove item from an array function removeItemFromArray(array, n) ( const newArray = (); for ( let i = 0; i < array.length; i++) ( if(array(i) !== n) ( newArray.push(array(i)); ) ) return newArray; ) const result = removeItemFromArray((1, 2, 3 , 4 , 5), 2); console.log(result);
Rezultāts
(1, 3, 4, 5)
Iepriekš minētajā programmā vienums tiek noņemts no masīva, izmantojot for
cilpu.
Šeit,
for
Cilpa tiek izmantota, lai cilpas cauri visiem elementiem, kas masīva.- Atkārtojot masīva elementus, ja noņemamais vienums nesakrīt ar masīva elementu, šis elements tiek virzīts uz newArray.
push()
Metode pievieno elementu newArray.
2. piemērs: Array.splice () izmantošana
// program to remove item from an array function removeItemFromArray(array, n) ( const index = array.indexOf(n); // if the element is in the array, remove it if(index> -1) ( // remove item array.splice(index, 1); ) return array; ) const result = removeItemFromArray((1, 2, 3 , 4, 5), 2); console.log(result);
Rezultāts
(1, 3, 4, 5)
Iepriekš minētajā programmā masīvs un noņemamais elements tiek nodots pielāgotajai removeItemFromArray()
funkcijai.
Šeit,
const index = array.indexOf(2); console.log(index); // 1
indexOf()
Metode atgriež indeksu konkrētā elementa.- Ja elements nav masīvā,
indexOf()
atgriež -1 . - Šīs
if
nosacījums pārbauda, vai elements, lai novērstu, ir masīvā. splice()
Metode tiek izmantota, lai novērstu elementu no masīva.
Piezīme : Iepriekš minētā programma darbojas tikai masīviem bez elementu dublikātiem.
Tiek noņemts tikai pirmais masīva elements, kas atbilst.
Piemēram,
(1, 2, 3, 2, 5)
rezultāti (1, 3, 2, 5)