如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
当前回答
对我来说,这适用于dom对象:
if(document.getElementsById('IDname').length != 0 ){
alert("object exist");
}
其他回答
两种方式。
用于局部变量的Typeof
你可以使用typeof测试本地对象:
if (typeof object !== "undefined") {}
全局变量窗口
你可以通过检查window对象来测试全局对象(在全局作用域中定义的对象):
if (window.FormData) {}
将文本框值设置为一帧到内联帧使用div对齐选项卡面板。 所以首先,在设置值之前,我们需要检查所选择的标签面板框架可用或不使用以下代码:
Javascript代码:
/////////////////////////////////////////
<script>
function set_TextID()
{
try
{
if(!parent.frames["entry"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["entry"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["education"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["education"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["contact"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["contact"].document.getElementById("form_id").value=setText;
}
}catch(exception){}
}
</script>
除了检查对象/变量是否存在之外,您可能希望提供一个“最坏情况”输出,或者至少将其捕获到警报中,这样就不会被忽略。
检查、提供替代方案和捕捉错误的函数示例。
function fillForm(obj) {
try {
var output;
output = (typeof obj !== 'undefined') ? obj : '';
return (output);
}
catch (err) {
// If an error was thrown, sent it as an alert
// to help with debugging any problems
alert(err.toString());
// If the obj doesn't exist or it's empty
// I want to fill the form with ""
return ('');
} // catch End
} // fillForm End
我创建这个也是因为我传递给它的对象可能是x, x.m, x.m[z],如果x.m不存在,则typeof x.m[z]将失败并报错。
我希望这能有所帮助。(顺便说一下,我是JS新手)
if (n === Object(n)) {
// code
}
0和null是隐式指针。如果你不做算术,比较,或打印'0'到屏幕上,就没有必要实际输入它。其隐含的。就像隐含的那样。出于同样的原因,Typeof也不是必需的。手表。
if(obj) console.log(“exist”);
我没有看到request for a not或else,因为它不包括。就像我喜欢不符合问题的额外内容一样。让我们保持简单。