A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Create a Two Dimensional Array in JavaScript
Q:

How to Create a Two Dimensional Array in JavaScript

0

How to Create a Two Dimensional Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Create an Array of Arrays

JavaScript does not support two-dimensional associative arrays. However, you can simulate the effect of two dimensional arrays in JavaScript by creating an array of arrays.

Let's take a look at the following example to understand how it basically works:

// Sample array
var arr = [
    ["a", "Apple"],
    ["b", "Banana"],
    ["c", "Cat"],
];

// Accessing array elements
console.log(arr[0][0]); // Prints: a
console.log(arr[0][1]); // Prints: Apple
console.log(arr[1][0]); // Prints: b
console.log(arr[1][1]); // Prints: Banana
console.log(arr[arr.length - 1][0]); // Prints: c
console.log(arr[arr.length - 1][1]); // Prints: Cat

Further, to create such arrays you could do something as shown in the following example:

// Creating an empty array
var arr = [];

// Populating array with values
arr[0] = ["a", "Apple"]; 
arr[1] = ["b", "Banana"]; 
arr[2]= ["c", "Cat"]; 

console.log(arr);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now