Sonia A. Sonia A. - 2 months ago 9
Javascript Question

Return but execute logic after it in a function?

I want getNum() to have the value, not console it within the function. If I do

return num[indexRandom]
in the function, the logic after that will break. Any clue?



$(document).ready(function() {
var num = ['1', '2', '3', '4', '5'];
var temp = [];
$("button").on("click", function() {
getNum();
});

function getNum() {
if (num.length <= 0) {
num = temp;
temp = [];
}
var indexRandom = Math.floor(Math.random() * (num.length));
console.log(num[indexRandom]); // instead of console how do return the value to the function
temp.push(num[indexRandom]);
num.splice(indexRandom, 1);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>button</button>




Answer

You need to return the value as the last line of the function after all other processing is done, but, as you may already realise, you can't just use return num[indexRandom] because the .splice() statement is removing that item from the array. So just use a temporary variable:

function getNum() {
    if (num.length <= 0) {
        num = temp;
        temp = [];
    }
    var indexRandom = Math.floor(Math.random() * (num.length));
    var selectedNum = num[indexRandom]);  // <-- add this
    temp.push(selectedNum);
    num.splice(indexRandom, 1);
    return selectedNum;                   // <-- add this
}

Alternatively, considering that the .splice() method returns an array containing the removed item, you could make use of that:

function getNum() {
    if (num.length <= 0) {
        num = temp;
        temp = [];
    }
    var indexRandom = Math.floor(Math.random() * (num.length));
    temp.push(num[indexRandom]);
    return num.splice(indexRandom, 1)[0];  // <-- note the [0] array access
}
Comments