2014-09-24 3 views
0

그래서 내가 만든 배열의 임의 문자열을 표시하려고합니다. 내 메시지의 계산 부분이 작동하고 표시해야하는 두 번째 부분과 배열에서 임의의 작업이 오류를 표시합니다. parseInt 및 Math.random 함수를 올바르게 사용하지 않았습니까? parseInt가 정수로 변환 한 이후에 숫자를 반올림하지 않아도됩니까? 여기임의의 작업을 표시하려고 할 때 HTMLInputElement 오류가 발생합니다.

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; 
+0

확인이 내가 볼 모든 – EsotericRider

답변

0

는 :

 tasks[tasks.length] = task; 

는 어레이로의 입력에 대한 레퍼런스를 추가한다. 따라서 실행될 때마다 동일한 입력에 다른 참조를 추가합니다. 아마도 당신은 의미 :

 tasks[tasks.length] = task.value; 

그렇게 작업 태스크 이름의 배열입니다.

 tasks.push(task.value); 

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

아를 업로드 : 내가 사용하는 거라고하지만 나머지는 잘해야한다. 고마워! – EsotericRider

관련 문제