Shawn123
Shawn123

Reputation: 457

Javascript Array Index Minus One

Is it allowed to do something like Array[i - 1] in javascript? Assuming that i and i-1 are proper indexes of the Array.

I am wondering because it seems to give me errors but I don't know if the error is how I refer to indexes.

Furthermore, is it possible to do something like Array[Array.length - 1]?

The actual error is with this:

input = input.split('\n');
    for (var i = 1; i < input.length; i++){
        for (var j = 0; j < input[i].length; j++){
            process.stdout.write(input[i][j]);
            process.stdout.write(input[i][j - 1]);
            process.stdout.write(input[i][input[i].length - 1 - j]);
            process.stdout.write(input[i][input[i].length - j]);
          if (input[i][j] - input[i][j - 1] !== input[i][input[i].length - 1 - j] - input[i][input[i].length - j]){

          }  
        }

    }

Of the process.stdout.write statements, only the first outputs anything.

Upvotes: 2

Views: 1857

Answers (1)

Jonas
Jonas

Reputation: 2249

Yes, it`s possible.

See here: https://jsfiddle.net/hca4cecc/

var myObj = [1, 2, 3, 4, 5];
alert(myObj[2-1+3]);

Edit: With your updated information: There is a bug. The [j-1] is -1 in the first loop and your code should crash.

Upvotes: 2

Related Questions