我希望getNum()拥有该值,而不是在函数内控制它。如果我在函数中执行return num[indexRandom]
,则之后的逻辑将会中断。任何线索?
$(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>
答案 0 :(得分:2)
我强烈建议不要这样做。我会将num[indexRandom]
存储为一个简单的变量,并在最后返回,但如果你按照自己的方式设置,那么使用它:
try { //Return
return num[indexRandom];
}
finally { //Code to run after returning. This will always happen after returning.
temp.push(num[indexRandom]);
num.splice(indexRandom,1);
}
答案 1 :(得分:1)
在完成所有其他处理后,您需要将值作为函数的最后一行返回,但是,正如您可能已经意识到的那样,您不能只使用return num[indexRandom]
因为.splice()
语句从数组中删除该项目。所以只需使用一个临时变量:
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
}
或者,考虑到.splice()
method返回包含已删除项的数组,您可以使用它:
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
}
答案 2 :(得分:0)
有解决方案:
function getNum() {
if (num.length <= 0) {
num = temp;
temp = [];
}
var indexRandom = Math.floor(Math.random() * (num.length));
var result = num[indexRandom];
//console.log(num[indexRandom]);
temp.push(num[indexRandom]);
num.splice(indexRandom, 1);
return result;
}