Index was outside the bounds of the array in C# and javascript(reason, examples and solutions)

Lionsure 2020-08-13 Original by the website

Regardless of the language, you will occasionally encounter an error message that the index exceeds the bounds of the array, that is, index was outside the bounds of the array(the used index of array exceeds the actual index of the array). For example, there are only 5 elements in an array, and the index (subscript) of array starts from 0. If the array is defined as a, and the value of a[5] is taken in this way, an out-of-bounds error of the array will be reported because the index of the last element is 4, and the last element should be a[4].

Of course, such low-level mistakes are rarely made in the actual development process. They are usually dynamic arrays generated by program operation, and index was outside the bounds of the array due to some circumstances that are not considered for the time being. Then I will give some examples of common indexes beyond the bounds of the array. In order to meet different needs, I will give examples of languages such as javascript and C#.

 

I. Javascript array index out of bounds

Example 1: The indexof array starts from 1, the code is as follows:

var arr = [1, 2, 3, 4, 5, 6];

 

Error:

for(var i = 1; i <= arr.length; i++){
              var tmp = arr[i];//When i = arr.length, the index of array is out of bounds
       }

 

Correct:

for(var i = 0; i < arr.length; i++){
              var tmp = arr[i];
       }

 

Example 2: The length of array is not judged, and the arbitrary value causes array index out of bounds

If you want to get all the div tags of webpage, without judging how many divs there are in advance, just use the subscript to get the value, the code is as follows:

var arr = document.getElementsByTagName("div");
       var temp = arr[1];

 

If there is no div or only one in the webpage, arr[1] will cause an array out of bounds error. The correct code should be judged by adding:

if(arr.length > 1){
              var temp = arr[1];
       }

 

 

II. Index was outside the bounds of the array in C#

If you want to get all text files in a folder, if you use the length of array to get the last element, an error which index was outside the bounds of the array will occur. The code is as follows:

/// <summary>
       /// C# get all text files in a folder
       /// </summary>
       /// <param name="path">Folder path</param>

       private void GetTxtFiles(string path)
       {
              DirectoryInfo di = new DirectoryInfo(path);
              FileInfo[] arrFi = di.GetFiles("*.txt");

       //Error
              string temp = arrFi[arrFi.Length].Name;//Get the last element with the length of array, the index of array will be out of bounds

       //Correct
              string temp = arrFi[arrFi.Length - 1].Name;
       }

Call:

GetTxtFiles("G:\xq\test");