Quick Contact

    JavaScript Arrays

    Introduction

    Arrays are sophisticated variables that allow us to store many variables or groups of data under a single variable name. JavaScript arrays may hold any legal value, including texts, integers, objects, functions, and even other arrays, allowing for the creation of more complicated data structures like an array of objects or an array of arrays.

    Assume you wish to save colour names in your JavaScript code. Storing the colour names in a variables one by one may look like this:

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Storing Single Values< /title>
    < /head>
    < body>
    < script>
        // Creating variables
    var color1 = "Red";
    var color2 = "Green";
    var color3 = "Blue";
    
        // Printing variable values
    document.write(color1 + "< br>");
    document.write(color2 + "< br>");
    document.write(color3);
    < /script>
    < /body>
    < /html>
    

    Output

    Red
    Green
    Blue
    

    Although what if you need to save the state or city names of a country in variables, and this time there are more than three? It is difficult and tedious to save each of them in a distinct variable. Using so many variables at the same time and keeping track of them all will be a challenging effort. And here is where array comes into play. Arrays overcome this problem by storing many items or groups of data in an ordered structure.

    Creating an Array

    In JavaScript, the easiest approach to build an array is to enclose a comma-separated list of values in square brackets ([]), as demonstrated below:

    Syntax

    var myArray = [element0, element1, …, elementN];

    The Array() function Object() { [native code] } can also be used to generate an array, as seen in the following syntax. However, for the purpose of clarity, previous syntax is advised.

    var myArray = new Array(element0, element1, …, elementN);

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>Creating Arrays in JavaScript< /title>
    < /head>
    < body>
    < script>
        // Creating variables
    var colors = ["Red", "Green", "Blue"]; 
    var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    var cities = ["London", "Paris", "New York"];
    var person = ["Ajeet", "kumar", 29];
    
        // Printing variable values
    document.write(colors + "< br>");
    document.write(fruits + "< br>");
    document.write(cities + "< br>");
    document.write(person);
    < /script>
    < /body>
    < /html>
    

    Output

    Red,Green,Blue
    Apple,Banana,Mango,Orange,Papaya
    London,Paris,New York
    Ajeet,kumar,29
    

    Note:

    An array is an ordered collection of values. Each value in an array is called an element, and each element has a numeric position in an array, known as its index.

    Accessing the Elements of an Array

    The square bracket syntax can be used to access array items by index. An indexing is an integer which specifies the location of an object in an array.

    Array indexes start at zero. This implies that the first item in an array is kept at index 0 rather than index 1, the second item at index 1, and so on. Array indices begin at 0 and increase to the number of items minus one. As a result, an array of five components would have indices ranging from 0 to 4.

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Access Individual Elements of an Array< /title>
    < /head>
    < body>
    < script>
    var countries = ["India", "USA", "UK", "Italy", "Russia"];
    
    document.write(countries[0] + "< br>"); 
    document.write(countries[1] + "< br>"); 
    document.write(countries[2] + "< br>"); 
    document.write(countries[countries.length - 1]); 
    < /script>
    < /body>
    < /html>
    

    Output

    India
    USA
    UK
    Russia
    

    Getting the Length of an Array

    The length parameter of an array returns the total number of components present in the array. The length of an array has always been bigger than the index of any of its elements.

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Get the Length of an Array< /title>
    < /head>
    < body>
    < script>
    var countries = ["India", "USA", "UK", "Italy", "Russia"];
    document.write(countries.length); 
    < /script>
    < /body>
    < /html>
    

    Output

    5

    Looping Through Array Elements

    You may use a for loop to retrieve every element of the array sequentially, as seen below:

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Loop Through an Array Using For Loop< /title>
    < /head>
    < body>
    < script>
    var countries = ["India", "USA", "UK", "Italy", "Russia"];
    
    for(vari = 0; i< countries.length; i++){    
    document.write(countries[i] + "< br>"); 
        }
    < /script>
    < /body>
    < /html>
    

    Output

    India
    USA
    UK
    Italy
    Russia
    

    The for-of loop, introduced in ECMAScript 6, is a simpler way to iterate through array elements. We can also use a for-in loop to traverse through the array entries.

    Note:

    The for-in loop should not be used to iterate over an array where the index order is important. The for-in loop is optimized for iterating over object’s properties, you should better use a for loop with a numeric index or for-of loop.

    Adding New Elements to an Array

    Simply use the push() function to add a new element to the end of an array, as seen below:

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Add a New Element at the End of an Array< /title>
    < /head>
    < body>
    < script>
    var countries = ["India","UK","Italy","Russia"]; 
    countries.push("USA");
    
    document.write(countries + "< br>"); 
    document.write(countries.length); 
    < /script>
    < /body>
    < /html>
    

    Output

    India,UK,Italy,Russia,USA
    5
    

    Removing Elements from an Array

    The pop() function may be used to remove the final entry from an array. The value that was popped out is returned by this procedure. Here’s an illustration:

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Remove the Last Element from an Array< /title>
    < /head>
    < body>
    < script>
    var countries = ["India", "USA", "UK", "Italy", "Russia"];
    var last = countries.pop();
    
    document.write(last + "< br>"); 
    document.write(countries.length); 
    < /script>
    < /body>
    < /html>
    

    Output

    Russia
    4
    

    Note:

    The push() and pop() methods runs faster than unshift() and shift(). Because push() and pop() methods simply add and remove elements at the end of an array therefore the elements do not move, whereas unshift() and shift() add and remove elements at the beginning of the array that require re-indexing of whole array.

    Adding or Removing Elements at Any Position

    The splice() function is a powerful array technique that lets you add or remove members from any index.

    Syntax

    arr.splice(startIndex, deleteCount, elem1, …, elemN).

    This function requires three parameters: the first is the index at which to begin splicing the array; the second is the number of members to delete (use 0 if you don’t want to remove any elements); and the third is a set of replacement elements, which is also optional.

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Add or Remove Array Elements at any Index< /title>
    < /head>
    < body>
    < script>
    var countries = ["India", "USA", "UK"];
    var removed = countries.splice(0,1); // Remove the first element
    
    document.write(countries + "< br>"); // Prints: USA,UK
    document.write(removed + "< br>");   // Prints: India (one item array)
    document.write(removed.length + "< br>"); // Prints: 1
    
    removed = countries.splice(1, 0, "Russia", "Japan"); // Insert two items at position one
    document.write(countries + "< br>"); // Prints: USA,Russia,Japan,UK
    document.write(removed + "< br>"); // Empty array
    document.write(removed.length + "< br>"); // Prints: 0
    
    removed = countries.splice(1, 1, "Italy", "Australia"); // Insert two values, remove one
    document.write(countries + "< br>"); //Prints: USA,Italy,Australia,Japan,UK
    document.write(removed + "< br>"); // Prints: Russia (one item array)
    document.write(removed.length); // Prints: 1
    < /script>
    < /body>
    < /html>
    

    Output

    USA,UK
    India
    1
    USA,Russia,Japan,UK
    
    0
    USA,Italy,Australia,Japan,UK
    Russia
    1
    

    Creating a String from an Array

    In certain cases, you may just wish to produce a string by connecting the components of an array. The join() function may be used to do this. This method accepts an optional argument, which is a separator string between each element. If you leave out the separator, JavaScript will use the comma (,) by default. The following example demonstrates how it works:

    Example

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Join All Elements of an Array into a String< /title>
    < /head>
    < body>
    < script>
    var colors = ["India", "USA", "Russia"];
    
    document.write(colors.join() + "< br>"); 
    document.write(colors.join("") + "< br>"); 
    document.write(colors.join("-") + "< br>"); 
    document.write(colors.join(", ")); 
    < /script>
    < /body>
    < /html>	
    

    Output

    India,USA,Russia
    IndiaUSARussia
    India-USA-Russia
    India, USA, Russia
    

    You may also use the function toString() { [native code] } function to convert an array to a comma-separated string (). This technique, unlike join, does not take the separator parameter ().

    Extracting a Portion of an Array

    The slice() function may be used to remove a piece of an array (i.e. a subarray) while keeping the main array intact. This method, like arr.slice, requires two parameters: start index (index at which to begin extraction) and optional end index (index before which to terminate extraction) (startIndex, endIndex).

    Example:

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Extract All Elements from an Array beyond Specific Index< /title>
    < /head>
    < body>
    < script>
    var countries = ["India", "Pakistan", "Bangladesh", "China", "Srilanka"];
    
    document.write(countries.slice(2) + "< br>"); 
    document.write(countries.slice(-2) + "< br>"); 
    document.write(countries.slice(2, -1)); 
    < /script>
    < /body>
    < /html>
    

    Output

    Bangladesh,China,Srilanka
    China,Srilanka
    Bangladesh,China
    

    Merging Two or More Arrays

    The concat() method can be used to merge or combine two or more arrays. This method does not change the existing arrays, instead it returns a new array.

    Example:

    < !DOCTYPE html>
    < html lang="en">
    < head>
    < meta charset="utf-8">
    < title>JavaScript Merge Two Arrays< /title>
    < /head>
    < body>
    < script>
    var herbivores = ["Eephant", "Cow", "Zebra"];
    var carnivores = ["Tiger", "Wolf", "Lion"];
    
    
    var animals = herbivores.concat(carnivores); 
    document.write(animals); 
    < /script>
    < /body>
    < /html>
    

    Output

    Eephant,Cow,Zebra,Tiger,Wolf,Lion

    The concat() method can take any number of array arguments, so you can create an array from any number of other arrays.

    FAQS

    Q1. What are arrays in JavaScript?

    Arrays are a subset of objects. In JavaScript, the typeof operation returns “object” for arrays. JavaScript arrays, on the other hand, are best characterized as arrays. Arrays access their “elements” using integers.

    Q2. What is an array example?

    An array is a set of data with similar types. For example, if we want to store the names of 50 people, we can build a string array which can hold 50 names.

    String[] array = new String[50];

    Q3. Why do we need arrays in JavaScript?

    In JavaScript, an array is a single variable which stores several components. It is frequently used when we need to save a set of elements to retrieve them using a single variable.

    Q4. What is loop in JavaScript?

    In JavaScript, loops are used to conduct repeated activities based on a condition. Typically, conditions return true or false. A loop will execute until the specified condition returns false.

    Q5. What is array in simple language?

    An array is a group of related data components that are stored in adjacent memory regions. It is the most basic data structure since each data piece may be retrieved directly using just its index number.

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.