2016-08-15 60 views
0

將以下隨機代碼重構爲可重用方法的最佳方法是什麼?我想把這部分轉換成可重複使用的方法==>$scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)];創建可重用方法的問題

我試過以下,它不工作:

function randTarotImg(){ 
      $scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)]; 
}  
$scope.onClick = function() { 
    randTarotImg(); 
}; 

下面是相關的代碼塊:

.controller('TarotCtrl', function ($scope) { 

    $scope.tarotImg = []; 
     for (var i=1;i<=6;i++) { 
     $scope.tarotImg.push(i); 
    } 

    $scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)]; 

    $scope.onClick = function() { 
      $scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)]; 
    }; 

}) 

回答

1

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

 
function getRandomElement(arr) { 
 
    return arr[Math.floor(Math.random()*arr.length)]; 
 
} 
 

 
console.log(getRandomElement(arr));

就你的情況:

.controller('TarotCtrl', function($scope) { 

    $scope.tarotImg = []; 
    for (var i = 1; i <= 6; i++) { 
    $scope.tarotImg.push(i); 
    } 

    function getRandomElement(arr) { 
    return arr[Math.floor(Math.random()*arr.length)]; 
    } 

    $scope.randTarotImg = getRandomElement($scope.tarotImg); 

    $scope.onClick = function() { 
    $scope.randTarotImg = getRandomElement($scope.tarotImg); 
    }; 

}); 
+0

完美,謝謝。 –