2017-08-17 25 views
0

我在for循環中得到了下面的錯誤代碼,但是當我給iput + = checkedBoxes [1]。 ID staticaly意味着它正在請幫助,也提醒在for循環正在與S問題Uncaught TypeError:無法讀取屬性'id'undefined在saveSign

ERROR : Uncaught TypeError: Cannot read property 'id' of undefined at saveSign

function saveSign(){ 
    alert('asd') 
    var iput =[]; 
    var checkedBoxes = document.querySelectorAll('input[type=checkbox]'); 
    for (var s=1;s<=checkedBoxes.length;s++){ 
    iput+=checkedBoxes[s].id 
    } 
    console.log(iput) 
} 
+0

警報(S)內的循環工作, iput + = checkedBoxes [1] .id也在工作 –

+0

document.querySelectorAll('input [t ype = checkbox]')。無論如何檢查這樣得到document.querySelectorAll('input [type = checkbox]')。unchecked like that需要取消檢查複選框值 –

回答

1

的問題與做你的for循環的循環計數器。它從1開始,跳過第一個數組元素,然後進行到數組中索引不存在元素的長度。您可以使用for-of循環或回調來完全避免循環計數器。

我還注意到你在陣列上使用+=運算符(iput)。要將元素附加到數組,可以使用push方法。如果您需要字符串,請將iput設置爲空字符串('')並保留+=

最後,你省略了幾個分號。由於自動分號插入的缺陷,只要有可能就使用它們以避免意外行爲更容易。

使用正常的循環:

function saveSign() { 
    const iput = []; 
    const checkedBoxes = document.querySelectorAll('input[type="checkbox"]'); 
    for(let i = 0; i < checkedBoxes.length; i++) { 
    iput.push(checkedBoxes[i].id); 
    } 
    console.log(iput); 
} 

使用for-of循環:

function saveSign() { 
    const iput = []; 
    const checkedBoxes = document.querySelectorAll('input[type="checkbox"]'); 
    for(const checkedBox of checkedBoxes) { 
    iput.push(checkedBox.id); 
    } 
    console.log(iput); 
} 

使用forEach回調:

function saveSign() { 
    const iput = []; 
    const checkedBoxes = document.querySelectorAll('input[type="checkbox"]'); 
    checkedBoxes.forEach((checkedBox) => { 
    iput.push(checkedBox); 
    }); 
    console.log(iput); 
} 
+0

謝謝@ kamoroso94現在我正在使用for-of循環根據您的指導和它的工作正常 –

1

我想,當s到達陣列中的最後一個元素被拋出的錯誤。您應重複從0到checkedBoxes.length

for (var s = 0;s < checkedBoxes.length; s++){ 
    iput += checkedBoxes[s].id 
} 
+0

很好,謝謝@ mic4ael現在完美工作。 –

0

在JavaScript中,數組的索引從0到length-1。 就你而言,你的循環的最後一次迭代超出了你的數組範圍。

要解決所有的數組,你需要像這樣定義你的循環:

for (var s = 0; s < checkedBoxes.length; s++){ 

} 
+0

謝謝@Techniv現在的工作 –

相關問題