简体   繁体   English

Javascript,如何检查对象是否存在

[英]Javascript, how to check if object exists

I am making a script in Javascript script that gets a SQL response, then processes it. 我正在用Javascript脚本制作一个脚本,该脚本获取SQL响应,然后对其进行处理。 Basically, I want to check if the username value exists in result[1] . 基本上,我想检查用户名值是否存在于result[1] When it checks, it errors out and says that it does not exist. 当检查时,它会出错并说它不存在。 If it does not exist, I want it to return false, not stop the program. 如果不存在,我希望它返回false,而不是停止程序。

Here is the code: 这是代码:

if (result[1].username != undefined) {
    return true;
} else {
    return false;
}

I have tried using typeof(result1) == undefined , but it gives me the same error. 我尝试使用typeof(result1) == undefined ,但是它给了我同样的错误。

You could use the in operator . 您可以使用in运算符 For example: 例如:

 let trueObj = { username: 'Foo' }; let falseObj = { }; if ('username' in trueObj) { console.log('username found in trueObj'); } else { console.log('username not found in trueObj') } if ('username' in falseObj) { console.log('username found in falseObj'); } else { console.log('username not found in falseObj') } 

First, you have to make sure the result exists, otherwise you'd be indexing into undefined which would crash your application. 首先,您必须确保结果存在,否则您将被索引为undefined ,这将导致应用程序崩溃。

Second, you can make that check less verbose with: 其次,您可以通过以下方式使该检查变得不太详细:

return (result[1] && result[1].username)

which will return a falsey value if it doesn't exist, and whatever the username is, if it does. 如果不存在,则返回falsey值;如果存在,则返回任何用户名。

In case you need an explicit true to be what the function returns, you can coerce it: 如果您需要一个显式的true值作为函数返回的值,则可以强制它:

return (result[1] && (result[1].username && true))

I would make sure to refactor for readability, but that's the gist. 我将确保重构的可读性,但这就是要点。

First of all please check whether the result itself exists or not and make the corresponding & operator and i think this will definitely help 首先,请检查结果本身是否存在,并进行相应的运算符,我认为这肯定会有所帮助

if (result && result[1] && result[1].username) {
    return true;
} else {
    return false;
}

But if you don't want to make your code complex then you can try lodash library. 但是,如果您不想使代码复杂,则可以尝试使用lodash库。 https://lodash.com/ https://lodash.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM