0

I wanted to know how to find a particular element say element at this array[2][3] position. I tried displaying all the elements but dint know how to print a particular value. i tried displaying the value but it displays undefined. Can you please help me in displaying particular value.

var array1 = new Array(3);

//2D array creation
for (var i = 0; i < 3; i++) {
  array1[i] = new Array(3);
}

var abc = 1;
for (var i = 0; i < 3; i++) {
  for (var j = 0; j < 3; j++) {
    array1[i][j] = abc;
    abc = abc + 1;
  }
}

for (var i = 0; i < 3; i++) {
  for (var j = 0; j < 3; j++) {
    document.write(array1[i][j] + " ");    
  }

  //alert(array1[2][3]);
  document.write("<br/>");
}
<!DOCTYPE HTML>
  <html>
	<head>
	  <title>Array Comparison</title>
    </head>
    <body>
    </body>
  </html>

2
  • avoid creating arrays with Array constructor, as you are using loops you can use push() method to add an item Commented Sep 4, 2017 at 16:51
  • 2
    As I see you don't have the 3 index in your array: array[2][3]. Your array is a 3x3, so if you try to access your [3] index, it will try to access your fourth element, and thats result in undefined. The lastest element is array[2][2]. Commented Sep 4, 2017 at 16:52

2 Answers 2

1

If your array is like this:

[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

The [2][3] position doesn't exist. Your array is a 3x3, so if you try to access your [3] index, it will try to access your fourth element, and that results in undefined. The lastest element is array[2][2].

In Javascript your arrays are always zero based index. So your first element is on [0] position.

Sign up to request clarification or add additional context in comments.

Comments

0

array1 is [[1,2,3],[4,5,6],[7,8,9]][[1,2,3],[4,5,6],[7,8,9]][[1,2,3],[4,5,6],[7,8,9]]

So array array1[2] will try to retrieve the element from index 2 which is

[7,8,9][7,8,9][7,8,9]

array1[2][3] will try to retrieve element from 3 index that is 4th position ,from result of array1[2] there is no element in third index, so there is undefined

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.