如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
如何验证JavaScript中对象的存在?
以下工作:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误:
maybeObject没有定义。
当前回答
我刚刚测试了上面的typeOf例子,没有一个适合我,所以我用了这个:
btnAdd = document.getElementById("elementNotLoadedYet"); if (btnAdd) { btnAdd。textContent = "Some text here"; }其他{ 警报(“没有发现!”); }
其他回答
0和null是隐式指针。如果你不做算术,比较,或打印'0'到屏幕上,就没有必要实际输入它。其隐含的。就像隐含的那样。出于同样的原因,Typeof也不是必需的。手表。
if(obj) console.log(“exist”);
我没有看到request for a not或else,因为它不包括。就像我喜欢不符合问题的额外内容一样。让我们保持简单。
你可以安全地在未定义的变量上使用typeof操作符。
如果它被赋值,包括null, typeof将返回非undefined的值。Typeof总是返回一个字符串。
因此
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
将文本框值设置为一帧到内联帧使用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>
我觉得这样最简单
if(myobject_or_myvar)
alert('it exists');
else
alert("what the hell you'll talking about");
如果这是一个全局对象,你可以使用If (!window.maybeObject)