如何检查变量是否在 JavaScript 中加载? [英] How to check if a variable is loaded in JavaScript?

查看:53
本文介绍了如何检查变量是否在 JavaScript 中加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查看某个对象是否已加载,如果未加载,如何加载,如下所示?

How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?

if (!isObjectLoaded(someVar)) {
    someVar= loadObject();
}

推荐答案

如果它是一个对象,那么你应该能够检查它是否是 null未定义,如果是,则加载它.

If it is an object then you should just be able to check to see if it is null or undefined and then load it if it is.

if (myObject === null || myObject === undefined) {
   myObject = loadObject();
}

使用 typeof 函数也是一种选择,因为它返回提供的对象.但是,如果对象尚未加载,它将返回 null 或 undefined在可读性方面归结为个人喜好.

Using the typeof function is also an option as it returns the type of the object provided. However, it will return null or undefined if the object has not been loaded so it might boil down a bit to personal preference in regards to readability.

这篇关于如何检查变量是否在 JavaScript 中加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆