Angularjs 从对象访问对象
我试图在结果中访问usertype的值,但无法执行此操作。我尝试了下面这样的方法,其中获取的数据是下面的JSONAngularjs 从对象访问对象,angularjs,json,Angularjs,Json,我试图在结果中访问usertype的值,但无法执行此操作。我尝试了下面这样的方法,其中获取的数据是下面的JSON if(data.result.usertype === 2){ console.log("redirect to type 2 user") } else if(data.result.usertype === 3){ console.log("redirect to type 3 user") } JSON如下所示 { "success": true, "tok
if(data.result.usertype === 2){
console.log("redirect to type 2 user")
}
else if(data.result.usertype === 3){
console.log("redirect to type 3 user")
}
JSON如下所示
{
"success": true,
"token": "abc",
"result": {
"_id": "57bd7c857e8d30893a9fc45b",
"usertype": "2",
"created_date": "1472035973314"
}
}
您应该使用
==
,通常===
是严格的类型相等运算符。它不仅检查两个值是否相等,而且检查类型是否相同。在你的例子中,它是一个字符串
所以使用==
只检查是否相等
if(data.result.usertype == 2){
console.log("redirect to type 2 user")
}
编辑:
因为您已经知道result.usertype是一个字符串,所以可以使用相同的方法,如下所示使用它
if(data.result.usertype === "2"){
console.log("redirect to type 2 user")
}
如果@nsr确实知道JSON将保持这种状态,我会选择
data.result.usertype==“2”
。当您知道变量的类型时,最好使用严格相等。@ValLeNain是有效的,修改了答案