如何比较JavaScript中的值 [英] How to compare a value in javascript

查看:102
本文介绍了如何比较JavaScript中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一些Ajax操作中获取数据,并尝试使用javascript实际执行一些条件检查

I am getting data from some ajax operation, and trying to use javascript to do some conditional checks actually

所以当我从ajax打印响应时

so when i print the response from the ajax like

document.write(response)

结果

[object Object]

当我打印类似document.write(JSON.stringify(response))

结果

{"status":"failed","login":["This field is required."],"password":["This field is required."]}

所以上面是我要获取的实际数据

so above is the actual data i am getting what i am trying to do is

if(response.status === 'failed')
            window.location.href = response.next;
        else if ('login' in response && response['login']==["This field is required."])
           {
              $("#message").html(<p>Username is required</p>); 
           }
        else if ('password' in response && response['password']==["This field is required."])
           {
              $("#message").html(<p>Password is required</p>); 
           }

但是&&条件response['login']==["This field is required."]不起作用 那么如何在javascript中检查上述类型的值呢?

But the && condition response['login']==["This field is required."] is not working so how to check the value of above type in javascript ?

注意: * JavaScript新手*

Note: *New to javascript *

推荐答案

使用点运算符访问响应对象的不同属性.

Access the different properties of the response object using the dot operator.

response.login[0] === "This field is required."

只是让您知道这里发生了什么-您正在获取一个json对象.可以简单地使用.PropertyName访问json对象中的属性.您的登录属性是一个数组,并且您要访问数组中的第一项,因此您使用[0]索引器.最后,您正在比较字符串,因此javascript中的最佳做法是使用===运算符,该运算符将比较类型和值.

Just to let you know what's going on here - you're getting back a json object. Properties in a json object can be access by simple using .PropertyName. Your login property is an array, and ou you want to access the first item in the array, so you use the [0] indexer. Lastly, you're comparing strings, so best practice in javascript is to use the === operator, which will compare type and value.

这篇关于如何比较JavaScript中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆