pre*_*pra 3 javascript json node.js
我从服务器获取了一些JSON值,但我不知道是否会有特定的字段。
有时我会以这种形式得到答复
{
"regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
Run Code Online (Sandbox Code Playgroud)
有时我会收到这种形式的回复
{
"regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"vehicle": "yes"
}
Run Code Online (Sandbox Code Playgroud)
如何检查javascript对象中是否存在车钥匙?
由于您不知道对象是否存在,因此您可以检查response['prop']语法。您也可以检查点语法,就像上面所做的那样,但我更喜欢这种方式。我养成了这个习惯,因为response.prop除非编译器清楚地知道该属性,否则语法在 Typescript 中不起作用。
if (serverResponse && serverResponse['vehicle']) {
// vehicle key exists
// do your stuff
} else {
// vehicle key Does Not exist
// do your stuff
}
Run Code Online (Sandbox Code Playgroud)
有多种检查方法,例如:
const obj = {
"regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"vehicle": "yes"
};
Run Code Online (Sandbox Code Playgroud)
in运算符:if("vehicle" in obj){ -- }hasOwnProperty: if(obj.hasOwnProperty("vehicle")){ -- }if(obj["vehicle"]){ -- }或if(obj.vehicle){ -- }| 归档时间: |
|
| 查看次数: |
5898 次 |
| 最近记录: |