我如何在 JavaScript 中验证对象的存在?
以下代码可行:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误信息:
maybeObject
未定义。
我如何在 JavaScript 中验证对象的存在?
以下代码可行:
if (!null)
alert("GOT HERE");
但是这会抛出一个错误:
if (!maybeObject)
alert("GOT HERE");
错误信息:
maybeObject
未定义。
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
if(document.getElementsById('IDname').length != 0 ){
alert("object exist");
}
if (n === Object(n)) {
// code
}
if (maybeObject !== undefined)
alert("Got here!");
零和空值是隐式指针。如果你不进行算术运算、比较或将“0”打印到屏幕上,实际上没有必要输入它。它是隐含的。同样的原因,typeof也不是必需的。看看这个例子。
if(obj) console.log("存在");
我没有看到关于否定或其他方面的请求,因此未包括在内。尽管我喜欢超出问题范围的额外内容,但让我们保持简单。
if (!maybeObject)
- 但实际上,标题要求相反的情况。 - Armali使用 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");
或者,您可以开始使用我的独家exists()方法,从而能够做到被认为是不可能的事情。例如:
像这样的事情:exists("blabla")
,甚至:exists("foreignObject.guessedProperty.guessNext.propertyNeeded")
也是可能的...
let myobj = null
)。在这种情况下,访问对象的属性会导致运行时错误,这才是你真正感兴趣的。因此,虽然被接受的答案在技术上是正确的,并且获得了大量的分数,但它并没有任何实际价值。 - EML