如何设置“如果对象存在”健康)状况?
有没有办法检查对象是否存在?我不断收到“需要对象”错误。我知道该对象不存在,如果是这种情况,我想绕过我的代码的一部分。我不知道我没有尝试过...
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
有什么方法可以查看对象是否存在?
Is there some way to check if an object exists? I keep getting an "object required" error. I know the object does not exist and I would like to bypass a part of my code should that be the case. I don't know what I have not tried...
var codeName = document.getElementById('testCode');
//I have tried
if(codeName != null)
if(codeName.length != 0)
if(typeOf codeName != 'undefined')
if(!codeName)
if(codeName.value != null)
Is there any way to see if an object exists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
在
getElementById
调用之后,codeName
要么是 DOM 元素,要么是 null。您可以使用警报来查看哪个:所以
if (codename != null)
应该有效。错误是否在发生之前就发生了?我会尝试添加警报以在代码运行时查看值。或者在调试器中单步执行此代码。
After the
getElementById
call,codeName
is either a DOM Element or null. You can use an alert to see which:So
if (codename != null)
should work.Does the error happen before it gets that far? I would try adding alerts to see the values as the code runs. Or step through this code in a debugger.
尝试:
如果您想确保 codeName 是一个对象:
Try:
if you want to be sure codeName is an Object:
我在这里有一个工作示例: http://jsbin.com/uduxe4/15
I got a working example here: http://jsbin.com/uduxe4/15
我不知道
document
是什么,但您可以尝试类似的方法,在使用它之前测试它是否存在......
I don't know what
document
is, but you could try something likeso testing if it exists before you using it...
我没有做很多 JS 编码,但看起来你的 [i] 是问题所在。据我所知,[]用于访问数组的字段,而你没有数组。只需使用“代码”+ i
I don't do a whole lot of JS coding, but it seems like your [i] is the problem. As far as I know, [] is used for accessing a field of an array, and you don't have an array. Just use "code" + i
在 ruby 中,
nil
相当于false
。因此尝试仅检查:
if codeName
In ruby
nil
is equivalent tofalse
.So try to check just:
if codeName
try/catch 对你有用吗? 示例
Would a try/catch work for you? Example
也许尝试检查您的对象是否继承了您的函数所需的类型?像这样:
if(codeName is String)
Maybe try checking that your object inherits from the type your function needs? Like this:
if(codeName is String)