jeudi 1 septembre 2016

Store value in variable from an if statement within a switch statement case

I want to have a variable keep track of results from an if statement in every case of a switch statement. The problem is every time my case uses the initial value of the variable - 0, and not value given by the previous case, so I always get myNum = 1. I want to know what is a common solution to this problem.

I also tried this with an array var myArray = [false,false,false,false]; where case 1 changes myArray[0] = true, when if statement in case 2 returns true it changes myArray[1] = true, however the entire array is now [false,true,false,false], i.e. the changes from case 1 are not saved in the variable and it is instead using the initial variable value.

Both cases are the same if I log value to console outside of the switch statement.

$scope.clickItem = function(result){
var myNum = 0;
function addNum() {
  myNum++;
};

switch(currentString) {
    case string1:
    if($scope.img1 === result){
         addNum();
         console.log('myNum is ' + myNum); // <- It's 1
         $scope.currentString = $scope.val2;
     }
     else{
         console.log("Wrong..");
     }
    break;

    case $scope.val2:
    if($scope.img2 === result){
        addNum();
        console.log('myNum is ' + myNum); // <- It's 1 again, when it should be 2.
        $scope.currentString = $scope.val3;
     }
     else{
         console.log("Wrong..");
     }
    break;

    case $scope.val3:
    if($scope.img3 === result){
         addNum();
         $scope.currentString = $scope.val4;
     }
     else{
    console.log("Wrong..");
}
break;
}
...etc

Aucun commentaire:

Enregistrer un commentaire