我使用Math.random()生成1之间的随机数,但数组availableNumbers()
但是,当文档的innerHTML更新时,suggestNumber解析为undefined,
我尝试从randomNumber中减去1,但这并没有什么区别。
我已经检查了W3文档,看起来这是正确实现的......
如何最好地从数组中检索随机项?是否有比我想要实施的更好的实施?
var availableNumbers = ["0", "911"];
function numberSuggestion() {
var randomNumber = Math.random() * availableNumbers.length -1;
var suggestedNumber = availableNumbers[randomNumber];
document.getElementById("suggestion").innerHTML = "How about dialing " + suggestedNumber + "? Don't like this number? Click the button above again!";
}
答案 0 :(得分:0)
将Math.random()
乘以整数将产生[0,number]范围内的浮点值。您需要删除小数部分以获得整数部分:
var randomNumber = Math.floor(Math.random() * availableNumbers.length);
答案 1 :(得分:-1)
哟尝试这个功能:
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
/* save the value in the browser */
echo 'window.'+VarYouWantToKeep = $_POST['VarYouWantToKeep'];
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");