JavaScript Array

  • Last update:November 26, 2020
  • I. Description

    When using JavaScript, we sometimes need to manipulate arrays, such as creating arrays, traversing array elements, sorting, etc.

    This document will introduce some basic operations of arrays.

    II. Create an array

    1) The Array object is used to store multiple values in a single variable. The method of creating an array is as follows:

    var txt = new Array("I","love","FR");
    alert(txt);

    The above code will return I,love,FR


    2) There are many ways to create an array. You can also create an empty Array and then defined the value of each element:

    var txt = new Array();
    txt[0] = "I";
    txt[1] = "love";
    txt[2] = "FR";
    alert(txt);

    III. Traverse the array elements

    Traversing each element of an array can be realized by using a for loop. For example, we have an array named txt:

    var txt = new Array("I","love","FR");
    for(i=0;i<txt.length;i++)   
    {alert(txt[i]);}

    The code above can display all the array elements.You can change the code in the for loop according to your requirement.

    IV. Convert Array to String

    The toString() method can convert an array to a string and return the result. For example:

    var var txt = new Array("I","love","FR");
    var str = txt.toString();
    alert(str);

    V. Sorting the array

    Just call the sort() method of the array to sort its elements.

    If no parameters are used when calling this method, the elements in the array will be sorted alphabetically. If we want to sort the elements according to the numeric values, we can first define a function sortNumber(), and then call it in the form of sort(sortNumber) to achieve the goal:

    function sortNumber(a, b){
      return a - b
    }
    var arr = new Array(6)
    arr[0] = "10"
    arr[1] = "5"
    arr[2] = "40"
    arr[3] = "25"
    arr[4] = "1000"
    arr[5] = "1"
    document.write(arr.sort(sortNumber))

    The output is: 1,5,10,25,40,1000

    Attachment List


    Theme: Secondary Development
    • Helpful
    • Not helpful
    • Only read

    滑鼠選中內容,快速回饋問題

    滑鼠選中存在疑惑的內容,即可快速回饋問題,我們將會跟進處理。

    不再提示

    10s後關閉

    Get
    Help
    Online Support
    Professional technical support is provided to quickly help you solve problems.
    Online support is available from 9:00-12:00 and 13:30-17:30 on weekdays.
    Page Feedback
    You can provide suggestions and feedback for the current web page.
    Pre-Sales Consultation
    Business Consultation
    Business: international@fanruan.com
    Support: support@fanruan.com
    Page Feedback
    *Problem Type
    Cannot be empty
    Problem Description
    0/1000
    Cannot be empty

    Submitted successfully

    Network busy