我在一种奇怪的情况下被困了几个小时,从服务器接收到的 JSON 的一个数字属性未能通过简单的相等测试。
var form = {'answer':'','categoryDisplay':'dbAdmin','creationDate':null,'id':0,'question':'','techJobDisplay':null,'techJobId':65};
var selTechJobId = form.techJobId;
var thisVal = String(65);
var restoreVal = String(selTechJobId);
alert("thisVal : " + thisVal + " | typeof thisVal : " + typeof thisVal);
alert("restoreVal : " + restoreVal + " | typeof restoreVal : " + typeof restoreVal);
alert("thisVal === restoreVal : " + thisVal === restoreVal);
当我运行此命令时,第三个警报显示“false”。对我来说,它显然应该显示“true”。我显然错过了一些东西。
我已经在谷歌上搜索了几个小时,我发现其中大部分都是关于类型不匹配问题。正如您所看到的,我将它们显式转换为 String,因此这不应该是这里的问题。
最佳答案
通过使用:"thisVal === RestoreVal : "+ thisVal
,您正在连接字符串,因此您将 "thisVal === RestoreVal : 65"
与 “65”
关于Javascript比较从对象属性中获取的数字作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26689531/