【问题标题】:object HTMLInputElement error when trying to display random task尝试显示随机任务时对象 HTMLInputElement 错误
【发布时间】: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


【解决方案1】:

这里:

        tasks[tasks.length] = task;

您正在添加对数组输入的引用。因此,每次运行时,您都会为同一输入添加另一个引用。也许你的意思是:

        tasks[tasks.length] = task.value;

so tasks 是任务名称的数组。其余的应该没问题,尽管我会使用:

        tasks.push(task.value);

if (typeof output.textContent == 'string') {
  output.textContent = message;
} else {
  output.innerText = message;
}

【讨论】:

  • 啊,我明白了。非常感谢!
猜你喜欢
  • 2017-05-04
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多