javascript 无法读取未定义的属性“长度”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18366106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:39:08  来源:igfitidea点击:

Cannot read property 'length' of undefined

javascriptjquery-mobile

提问by Steven07

I've been looking at the other posts on this error but can't seem to figure it out in this situation. I'm trying to save to localstorage, but I get this error and it says that the "radio" variable is undefined, but it doesn't seem to be. I'm using JQMobile as well. Here's the fiddle: http://jsfiddle.net/KpbLD/Line 28 seems to be the problem.

我一直在查看有关此错误的其他帖子,但在这种情况下似乎无法弄清楚。我正在尝试保存到 localstorage,但出现此错误,它说“radio”变量未定义,但似乎不是。我也在使用 JQMobile。这是小提琴:http: //jsfiddle.net/KpbLD/第 28 行似乎是问题所在。

Here's the function:

这是函数:

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;

};

回答by Dmitry Minkovsky

You can't read properties of undefined. It doesn't have properties, typically (see http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/).

您无法读取undefined. 它通常没有属性(参见http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/)。

So, before you try to read its length, make sure it's not undefined. Or that it has a length, like

因此,在您尝试阅读它之前length,请确保它不是未定义的。或者它有一个length,比如

if (obj.length) { your code }

This presumes that objis not undefined. If you're not sure about that either, then:

这假定obj不是undefined。如果您对此也不确定,那么:

if (obj && obj.length) { your code }

回答by Ben McCormick

document.forms[0].acoustic

Doesn't exist and therefore is undefined. When you set radios to that and then try to find the length, it fails.

不存在,因此未定义。当您将收音机设置为那个然后尝试找到长度时,它会失败。

You probably need to be looking for a different object, or at least checking to see if the object exists before attempting to iterate over it.

您可能需要寻找不同的对象,或者至少在尝试对其进行迭代之前检查该对象是否存在。

回答by Deepa

Please check the typeof variable(radios). It seems to be object. This error won't come if it is an array.

请检查typeof variable(radios). 好像是对象。如果它是一个数组,则不会出现此错误。