# How to get value at given array position

I have a function that needs the values stored in an array to work properly. Problem is, it’s currently getting the
array position of the value (i.e. let’s say `array[1] = 3` I need the 3, but get the 1). How do I go about checking the data stored at the position, instead of checking the position?

Here’s a little snippet from script to show how I’m trying to use it:

``````CheckRoll.prototype.getResults = function()
{
this.results = [1,2,4,5,6];

for(i=0;i<this.results.length;i++)
{
if(i >= 1)
{
j = i - 1;
}
else
{
j = null;
}

if(this.results[j] !== this.results[i] - 1 && this.straight < 4)
{
this.straightCount = 1;
}
else if(this.results[j] === this.results[i] - 1)
{
this.straightCount++;
}
``````

In the situation I create by making the array 1,2,4,5,6, `straghtCount` should set to 1 after seeing that `results[1] = 2` and `results[2] = 4`, but it doesn’t because what it’s getting is `results[1] === results[2] - 1`.

On the first iteration of the loop, you are accessing `this.results[null]` will give you undesirable behaviour.

In this case, it would be better if you started the `i` loop at 1 and not 0. That way, `i-1` is always going to be 0 or above.

Right, but I need to access all 5 points in the array. The problem stems from the fact that i and j are positions in the array rather than the data that’s at the position. So as I mentioned above, if the results array is `results = [1,2,4,5,6];` straightCount should tick up to 1 after checking position 0 and 1 because the values in those locations increase by 1, but when it checks position 1 and 2, it should reset because the values increase by 2. A similar problem would occur if j had a value right away, it needs to be more or less non existent until i has passed the first value in the array.

Basically `i = 0` needs to actually be `i = 1` and `i = 1` needs to be `i = 2`, which at this point would mean `j = 1`.

Got it. Instead of checking just `i`, I need to check `results[i]`.

This is how I would do it:

``````    this.results = [1,2,3,4,5];

var isStraight = true;
for(var i = 1; i < this.results.length; i++)
{
if (this.results[i-1] != this.results[i] - 1) {
isStraight = false;
break;
}
}

if (isStraight) {
console.log('Straight');
} else {
console.log('Not straight');
}
``````

EDIT: Redacting entire post I originally had here. I see what you’re doing, but I need to know how long the straight is because there’s two different kinds of straights a player can roll. The method is the same either way, you just cut out some extra steps I took that are probably unnecessary.

In which case:

``````this.results = [1,2,3,4,5];

var straightCount = 1;
for(var i = 1; i < this.results.length; i++)
{
if (this.results[i-1] != this.results[i] - 1) {
break;
} else {
straightCount += 1;
}
}

console.log(straightCount);
``````

Yep, like I said same method just shorter.