簡體   English   中英

無法讀取未定義的屬性“長度”

[英]Cannot read property 'length' of undefined

我一直在尋找有關此錯誤的其他帖子,但在這種情況下似乎無法解決。 我正在嘗試保存到localstorage,但出現此錯誤,並說“ radio”變量未定義,但似乎不是。 我也在使用JQMobile。 這是小提琴: http : //jsfiddle.net/KpbLD/第28行似乎是問題所在。

功能如下:

var getSelectedRadio = function(){
        var radios = document.forms[0].acoustic;
        for(var i=0, j=radios.length; i<j; i++){
            if(radios[i].checked) {
            console.log(acousticValue);
                acousticValue = radios[i].value;

            }
        }
        return acousticValue;

};

您無法讀取undefined屬性。 通常,它沒有屬性(請參閱http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/ )。

因此,在嘗試讀取它的length ,請確保它不是未定義的。 或者它有一個length ,例如

if (obj.length) { your code }

這假定obj不是undefined 如果您不確定,則:

if (obj && obj.length) { your code }
document.forms[0].acoustic

不存在,因此未定義。 當您將收音機設置為該長度,然后嘗試查找長度時,它將失敗。

您可能需要尋找其他對象,或者至少在嘗試對其進行迭代之前檢查該對象是否存在。

請檢查typeof variable(radios) 這似乎是對象。 如果是數組,則不會出現此錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM