【问题标题】:Why does P != "P" in my JSON response? [closed]为什么 P != "P" 在我的 JSON 响应中? [关闭]
【发布时间】:2018-06-11 04:01:20
【问题描述】:

问题:

由于某种奇怪的原因,我的 JSON 中的“P”似乎不等于“P”,但“P”==“P”返回 true。这毫无意义。

某处一定有一些数据类型问题。

如何确保response.charAt(0) == "P" 返回true


代码:

$.ajax({
        type: "POST",
        url: "/1/1",
        data: someData,
    }).done(function(response) {
        console.log("p" == "P"); //prints false
        console.log("P" == "P"); //prints true
        console.log("RESPONSE: "+response); //prints "Primary"
        console.log("RESPONSE FIRST LETTER: "+response.charAt(0)); //prints P 
        console.log("RESPONSE BOOL P :"+response.charAt(0)=="P"); 
        //
        //false for some reason, should be true 
        //
        if (response.charAt[0] == "P") {
            console.log("1");
            localStorage.setItem("error_msg_local", message);
        } else if (response.charAt[0] == "L") {
            localStorage.setItem("success_msg_local", message);
            console.log("2");
        } else {
            localStorage.setItem("error_msg_local", "Internal error. Please try again.");
            console.log("3");
            // 3 gets logged when it should have been 1
        }
    });

【问题讨论】:

  • 问题是什么
  • 为什么投反对票?
  • @Sajeetharan "我如何确保 response.charAt(0) == "P" 返回 true ?"
  • 这是一个错字,因为你已经评论了 charAt(0)
  • @Sajeetharan 是的。错字。

标签: javascript jquery json ajax string


【解决方案1】:
response.charAt[0]

这会将charAt 视为一个数组。注意()[] 之间的区别。

您应该使用括号来使用 charAt 。功能

response.charAt(0)

【讨论】:

  • 确实是错字。谢谢。
【解决方案2】:

正如你在评论中提到的,应该是.charAt

改变

来自

if (response.charAt[0] === "P")

收件人

if (response.charAt(0) === "P") 

【讨论】:

    猜你喜欢
    • 2015-03-26
    • 2016-01-23
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2018-04-07
    • 2020-06-01
    • 1970-01-01
    • 2018-04-29
    相关资源
    最近更新 更多