【发布时间】:2014-09-24 06:22:48
【问题描述】:
所以我试图显示我创建的数组中的随机字符串。我的消息的计数部分有效,它应该显示的第二部分和我数组中的随机任务显示错误。我没有正确使用 parseInt 和 Math.random 函数吗?我不必四舍五入,因为 parseInt 将其转换为整数,对吗?
var tasks = [];
// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
'use strict';
// Get the task:
var task = document.getElementById('task');
// Reference to where the output goes:
var output = document.getElementById('output');
// For the output:
var message = '';
if (task.value) {
// Add the item to the array:
tasks[tasks.length] = task;
var randomNum = tasks.length;
var randomTask = parseInt((Math.random() * randomNum), 10);
var randomMsg = tasks[randomTask];
// Update the page:
message = 'You have ' + tasks.length + ' task(s) in your to-do list.\n';
message += 'Random Task: ' + randomMsg;
if (output.textContent !== undefined) {
output.textContent = message;
} else {
output.innerText = message;
}
} // End of task.value IF.
// Return false to prevent submission:
return false;
} // End of addTask() function.
// Initial setup:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;
【问题讨论】:
-
好的,上传所有内容
标签: javascript arrays parseint