JavaScript implements methods for multidimensional arrays

  • 2020-03-29 23:53:01
  • OfStack

In C#, define the multidimensional array, can be achieved by such simple code:

int[,]myArray=new int[4,5]; 

You can't directly define multidimensional arrays in JavaScript, so how do you do that?
First, define a one-dimensional array:

var myArray=new Array(); 

Then the members of the one-dimensional array are defined as arrays (redefined because JavaScript is weakly typed) :

myArray[0]=new Array(); 

So far, we have defined a two-dimensional array with the first index of 0. If we want to use the two-dimensional array with the first index of 1, we still need to define:

<span style="font-family:Calibri;">myArray[1]=new Array();</span> 

The following is an example of JavaScript multi-dimensional array application, which USES multi-dimensional array to store multiple choice questions and answers:

<script type="text/javascript"> 
        //Read whether the answer is correct or not
        function answerCorrect(questionNumber, answer) { 
            var correct = false; 
            if (answer == answer[questionNumber]) 
                correct = true; 

            return correct; 

        //Defines an array of questions and an array of answers to store questions and options
        var questions = new Array(); 
        var answers = new Array(); 

        //Problem 1 defines a member with an index of 0 as a two-dimensional array
        questions[0] = new Array(); 

        //So we're going to define a member of a two-dimensional array
        questions[0][0] = "the Beatles were:"; 
        // The answer  
        questions[0][1] = "A Sixties rock group from Liverpool"; 
        questions[0][2] = "Four musically gifted insected"; 
        questions[0][3] = "German Cars"; 
        questions[0][4] = "I don't know"; 

        //The answer to question 1
        answers[0] = "A" 

        //Question 2
        // define Question 2
        questions[1] = new Array(); 
        questions[1][0] = "Homer Simpon's favorite food is:"; 
        questions[1][1] = "Fresd slead"; 
        questions[1][2] = "Doughnuts"; 
        questions[1][3] = "sea food"; 
        questions[1][4] = "apples"; 

        //The answer to question 2
        answers[1] = "B"; 

        //Prompt initialization is complete
        alert("Array Initiallized"); 


PS: recently in the process of learning JavaScript, I often use notepad to write programs, and then change to the format of. HTM to run, which is not as efficient as VS or DreamWeaver, mainly without smart tips and highlighting. But you can remind yourself to pay attention to every little detail, such as JavaScript case-sensitive, how to write Html markup and so on.

Related articles: