Vargjet janë variabla që mund të mbajnë një ose më shumë vlera. Llojet e vlerave të zakonshme në vargje janë vargu, numri, boolean dhe objektet. Ju gjithashtu mund të keni variabla të llojeve të ndryshme në një grup.

const colorsArray = ["Red", "Green", "Blue"];
const numbersArray = [10, 4, 3, 2, 45];
const objectsArray = [
  {
    "color": "Red",
    "number": 10,
    "isRed": true
  },
  {
    "color": "Green",
    "number": 21,
    "isRed": false
  },
];

Një sintaksë tjetër për të krijuar një grup:

const colorsArray = new Array("Red", "Green", "Blue");

Qasja dhe ndryshimi i elementeve të grupit

Ju aksesoni një element grupi duke iu referuar numrit të indeksit: indekset fillojnë me 0, po programuesit fillojnë të numërojnë me 0.

const colorsArray = ["Red", "Green", "Blue"];
const redColor = colorsArray[0];
const greenColor = colorsArray[1];
const blueColor = colorsArray[2];

Vetitë dhe metodat e vargjeve në JavaScript

Vargjet në JavaScript kanë mjaft mjete të dobishme për të zgjedhur:

const colorsArray = ["Red", "Green", "Blue"];
colorsArray.length;   // Returns the number of elements = 3
colorsArray.sort();   // Sorts the array
colorsArray.reverse();   // Reverses the elements in an array
colorsArray.push("Purple");   // Adds an element to the array
colorsArray.pop();   // Removes an element from the end of the array

Duke xhiruar nëpër një grup JavaScript

const colorsArray = ["Red", "Green", "Blue"];
for (let color in colorsArray) {
  alert( arr[key] ); // Red, Green, Blue
}

Shtimi i kushtëzuar i artikujve në një grup në JavaScript

Duke përdorur operatorin e përhapjes:

const colorsArray = [
  "Red",
  ...true ? ["Green"] : [],
  ...false ? ["Blue"] : [],
]

console.log(colorsArray); // Red, Green

Duke përdorur metodën e shtytjes:

const colorsArray = [
  "Red",
]

if (true) {
  colorsArray.push("Green");
}

if (false) {
  colorsArray.push("Blue");
}

console.log(colorsArray) // Red, Green