[英]Which is the best way to check if an object has property
I want to ask which is the right way to check if an ajax response object has a property . 我想问问哪种是检查ajax响应对象是否具有属性的正确方法。 I googled and what I found is that there are different ways to approach this.
我用谷歌搜索,发现有多种方法可以解决此问题。
For example: 例如:
if(ajaxResponse.hasOwnProperty('someProperty')){
//do blah blah
}
but there are other ways for sure, for example : 但是还有其他确定的方法,例如:
if(typeof ajaxResponse.someProperty !== 'undefined')){
//do blah blah
}
So I am guessing there are some pros and cons can you please share these with me. 因此,我猜有一些优点和缺点,请您与我分享。
Thanks 谢谢
Let's say your an object is something like the one showed below... 假设您的对象类似于下面显示的对象...
var person = {
name: "Nicholas"
};
there are plenty of methods using which you can check for this.... 有很多方法可以用来检查...。
Method 1 方法1
person.hasOwnProperty("name")
Method 2 方法二
if ("name" in person){
//property exists
}
Method 3 (NOT RECOMMENDED) 方法3(不推荐)
//doesn't accurately test for existence
if (person.name){
//yay! property exists!
}
If you just want to check for the existence of properties, and not necessarily what their value might be, then you have two safe options: hasOwnProperty()
and the in
operator. 如果只想检查属性的存在,而不必检查它们的值可能是什么,则有两个安全选项:
hasOwnProperty()
和in
运算符。 The hasOwnProperty()
property method should be used if you want to detect own properties only. 如果只想检测自己的属性,则应使用
hasOwnProperty()
属性方法。 If you want to test property existence and don't care if it's an own property or an object property, then the in operator is the one to use. 如果您想测试属性的存在,而不必关心它是一个自己的属性还是一个对象属性,那么in运算符就是要使用的运算符。
$.ajax({
type: "POST",
url: "frmSample.aspx/LoadSample",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var jsonData = $.parseJSON(data.d);
},
error: function OnError(xhr) {
}
});
Suppose if any error occurs in ajax call the response goes directly to the error , it will not go to success . 假设如果ajax调用中发生任何错误,则响应将直接针对该错误 ,它将不会成功 。 If empty data is passed as result, then data.d would be ''.
如果将空数据作为结果传递,则data.d将为。 So, it is neccessary to check whether data.d is empty or not before parsing.
因此,有必要在解析之前检查data.d是否为空。 If the resultant is Json, parse the json as follows
如果结果是Json,则按以下方式解析json
var jsonData = $.parseJSON(data.d);
If jsonData.length == 0
, no property is there for the result. 如果
jsonData.length == 0
,则结果没有属性。 There are many ways of checking the property in json response. 检查json响应中的属性的方法有很多。 This is one way of doing it in simple.
这是一种简单的方法。 Directly check the jsonData.
直接检查jsonData。 PropertyName != null or not.
PropertyName !=是否为null。
the easiest way imo is: imo最简单的方法是:
if (ajaxResponse.someProperty){
//do stuff
}
Except the property is a boolean. 除了该属性是布尔值。 Then this would not necessarily work as wanted :)
然后,这不一定会按需要工作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.