Aje*_*esh 304 javascript json
amt: "10.00"
email: "sam@gmail.com"
merchant_id: "sam"
mobileNo: "9874563210"
orderID: "123456"
passkey: "1234"
Run Code Online (Sandbox Code Playgroud)
以上是我正在处理的JSON对象.我想检查'merchant_id'键是否存在.我尝试了下面的代码,但它不起作用.有什么方法可以实现吗?
<script>
window.onload = function getApp()
{
var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');
//console.log(thisSession);
if (!("merchant_id" in thisSession)==0)
{
// do nothing.
}
else
{
alert("yeah");
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
Ana*_*Jha 543
试试这个,
if(thisSession.hasOwnProperty('merchant_id')){
}
Run Code Online (Sandbox Code Playgroud)
JS对象thisSession应该是这样的
{
amt: "10.00",
email: "sam@gmail.com",
merchant_id: "sam",
mobileNo: "9874563210",
orderID: "123456",
passkey: "1234"
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到详细信息
Pau*_*aul 72
根据您的意图,有几种方法可以做到这一点.
thisSession.hasOwnProperty('merchant_id'); 将告诉你thisSession本身是否具有该密钥(即它不是从其他地方继承的东西)
"merchant_id" in thisSession 会告诉你thisSession是否有钥匙,无论它到底在哪里.
thisSession["merchant_id"]如果密钥不存在,或者由于任何原因其值的计算结果为false,则返回false(例如,如果它是文字false或整数0,依此类推).
小智 25
你可以这样做:
if("merchant_id" in thisSession){ /** will return true if exist */
console.log('Exist!');
}
Run Code Online (Sandbox Code Playgroud)
或者
if(thisSession["merchant_id"]){ /** will return its value if exist */
console.log('Exist!');
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*Sam 18
(即使我迟到了,我也想指出这一点)
原来你试图找到一个'不在'的问题.看起来我从事的研究(下面的2个链接)不支持.
所以,如果你想做一个'不在':
("merchant_id" in x)
true
("merchant_id_NotInObject" in x)
false
Run Code Online (Sandbox Code Playgroud)
我建议只将表达式==设置为您要查找的内容
if (("merchant_id" in thisSession)==false)
{
// do nothing.
}
else
{
alert("yeah");
}
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in http://www.w3schools.com/jsref/jsref_operators.asp
Kai*_*las 15
类型检查也可以:
if(typeof Obj.property == "undefined"){
// Assign value to the property here
Obj.property = someValue;
}
Run Code Online (Sandbox Code Playgroud)
Sye*_*yed 10
此代码导致 esLint 问题: no-prototype-builtins
foo.hasOwnProperty("bar")
Run Code Online (Sandbox Code Playgroud)
这里的建议方法是:
Object.prototype.hasOwnProperty.call(foo, "bar");
Run Code Online (Sandbox Code Playgroud)
我会稍微更改您的if语句并起作用(也适用于继承的obj-在代码段中查看)
if(!("merchant_id" in thisSession)) alert("yeah");
Run Code Online (Sandbox Code Playgroud)
if(!("merchant_id" in thisSession)) alert("yeah");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
498036 次 |
| 最近记录: |