2

I am trying to make a Yahtzee game. I have a function to check if the dice rolled are a small straight.

var sortedDice = rollDice().sort(); // rollDice() generates an array with 5 random numbers

My function to determine if there is a small straight:

function isSmStraight(checkSmStraight){
    var smStraight = false;

    var i = 1;
    var j = 0;

    //will remove a die if there are duplicates
    while(i < checkSmStraight.length){
        if (checkSmStraight[i] == checkSmStraight[j]){
            i++;
        } else {
            j++;
            checkSmStraight[j] = checkSmStraight[i];
            i++;
        }//end if else
    }//end while loop that moves duplicates to last index of array
    checkSmStraight.pop();//removes last index of array

    if (isLgStraight(checkSmStraight) == true){
        smStraight = true;
    } else if (checkSmStraight.length == 4 && checkSmStraight[checkSmStraight.length-1] - checkSmStraight[0] == 3){
        smStraight = true;
    }//end if else if
    return smStraight;
}//end function isSmStraight()

I have copied sortedDice to another array, fourDice, that I can use to call isSmStraight(). I want just this function to use the four-index array, but it always messes with sortedDice, so the rest of the program uses the four-dice array. (This isn't the whole program, just the parts I thought are relevant. Also, the program is finished, I'm just trying to get the scoring functions right first).

3
  • You must define global var outside if your function, like var newvar = ""; function test() { newvar = "new text"; } Commented Dec 25, 2014 at 19:20
  • You're probably passing a reference, not a new array, use .slice() to create a copy. Commented Dec 25, 2014 at 19:22
  • Yes, the global variables are defined outside the function. Using .slice() worked perfectly. Thanks both for the quick responses. Commented Dec 25, 2014 at 19:37

1 Answer 1

2

Arrays are by default, passed be reference in JavaScript. So if you're just doing something like var fourDice = sortedDice and then edit fourDice, sortedDice will also get edited Please also put the code where you're copying sortedDice to fourDice in the question.

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

1 Comment

That's exactly what I was doint wrong. Using .slice() worked perfectly. Now I just need to figure out how to mark this as solved (new to the site).

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.