简体   繁体   English

检查js / jQuery是否确实存在对象(不是元素)

[英]Check if an object (not an element) really exists with js/jQuery

I got this string of code, data is value returned inside a success callback in an ajax environment: 我得到了以下代码字符串,数据是在ajax环境中的成功回调内返回的值:

$('#cpt_rspp_value').text(data.Payload.Clerks.rspp.full_name)
$('#cpt_ddl_value').text(data.Payload.Clerks.ddl.full_name)
$('#cpt_rls_value').text(data.Payload.Clerks.rls.full_name)
$('#cpt_mc_value').text(data.Payload.Cler.mc.full_name)
$('#cpt_se_value').text(data.Payload.Clerks.se.full_name)

If, rspp really exists inside the DB the object data.Payload.Clerks.rspp.full_name will be present, so I can put it in right place (ie: #cpt_rspp_value ). 如果rspp确实存在于数据库中,则将出现对象数据data.Payload.Clerks.rspp.full_name将存在,因此我可以将其放在正确的位置(即: #cpt_rspp_value )。 But, alas, if that object doesn't exist, the js interpreter will stop, and so, even if next objects data.Payload.Clerks.ddl.full_name , data.Payload.Clerks.rls.full_name and so on, will be present, that row will never been processed. 但是,可惜的是,如果该对象不存在,则js解释器将停止,因此,即使下一个对象data.Payload.Clerks.ddl.full_namedata.Payload.Clerks.rls.full_name等等,也将是目前,该行将永远不会被处理。

I should "if" any lines, but how? 我应该“如果”有任何行,但是如何? if(data.Payload.Clerks.rspp.full_name) and if(data.Payload.Clerks.rspp.full_name != null) don't resolve the issue. if(data.Payload.Clerks.rspp.full_name)if(data.Payload.Clerks.rspp.full_name != null)无法解决问题。 What can I do? 我能做什么?

You can use typeof javascript operator to check if the object defined, 您可以使用typeof javascript运算符检查是否定义了对象,

if(typeof data.Payload.Clerks.rspp.full_name != 'undefined')

or 要么

if(typeof data.Payload.Clerks.rspp != 'undefined')

For checking if it's strictly an object 用于检查是否严格来说是一个object

if(typeof myobject === 'object')

In your case, check for string type 根据您的情况,检查string类型

if( typeof data.Payload.Clerks.rspp.full_name === 'string')

Personal opinion - you could just use if(rspp.full_name) since it's a trivial check in the larger scheme of things. 个人观点-您可以只使用if(rspp.full_name)因为这在较大的方案中是很简单的检查。 (from what it seems like in the question) :) (从问题中看起来):)

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

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