如何查看某个对象是否已加载,如果没有,如何加载,如下所示?
if (!isObjectLoaded(someVar)) {
someVar= loadObject();
}
如何查看某个对象是否已加载,如果没有,如何加载,如下所示?
if (!isObjectLoaded(someVar)) {
someVar= loadObject();
}
如果它是一个对象,那么您应该能够检查它是否为空或未定义,然后如果是则加载它。
if (myObject === null || myObject === undefined) {
myObject = loadObject();
}
使用typeof函数也是一种选择,因为它返回所提供对象的类型。但是,如果对象尚未加载,它将返回null 或 undefined,因此在可读性方面可能会归结为个人偏好。
if(typeof(o) != 'object') o = loadObject();
myObject = myObject || loadObject();
我不确定您所说的“已加载”是什么意思...变量是否object
存在并且根本没有您想要的类型?在这种情况下,你会想要这样的东西:
function isObjectType(obj, type) {
return !!(obj && type && type.prototype && obj.constructor == type.prototype.constructor);
}
然后使用if (isObjectType(object, MyType)) { object = loadObject(); }
.
如果object
在您的测试之前没有填充任何内容(即 - typeof object === 'undefined'
),那么您只需要:
if ('undefined' === typeof object) { object = loadObject(); }
您可能想查看是否定义了给定对象
特别是如果它在一个异步线程中完成,并带有 setTimeout 来检查它何时出现。
var generate = function()
{
window.foo = {};
};
var i = 0;
var detect = function()
{
if( typeof window.foo == "undefined" )
{
alert( "Created!");
clearInterval( i );
}
};
setTimeout( generate, 15000 );
i = setInterval( detect, 100 );
理论上应该检测 window.foo 何时存在。
If by loaded you mean defined, you can check the type of the variable with the typeof function. HOWEVER typeof has a few quirks, and will identify an Object, an Array, and a null as an object
alert(typeof(null));
Identifying a null as a defined object would probably cause your program to fail, so check with something like
if(null !== x && 'object' == typeof(x)){
alert("Hey, It's an object or an array; good enough!");
}
如果要检测自定义对象:
// craete a custom object
function MyObject(){
}
// check if it's the right kind of object
if(!(object instanceof MyObject)){
object = new MyObject();
}
您也可以只使用快捷方式if(obj)
typeof(obj)
将在其他可能的值中返回类对象的“对象”。
if (!("someVar" in window)) {
someVar = loadObject();
}
will tell you whether any JS has previously assigned to the global someVar
or declared a top-level var someVar
.
That will work even if the loaded value is undefined
.