Javascript 为什么代码不能正确识别字符串中的数字和/或字母?

Javascript 为什么代码不能正确识别字符串中的数字和/或字母?,javascript,string,Javascript,String,我想设计一种允许代码识别字母的方法,我的代码是: var thingToTest = "Some Random String" var thing = thingToTest.charAt(0); if (thing = "some random letter that isn't in the code") { alert("This should not come up..."); }; 然而,不管信是否正确,警报总是会弹出。我已经更新了我所有的软件,重新启动了我的电脑,但它从来

我想设计一种允许代码识别字母的方法,我的代码是:

var thingToTest = "Some Random String"
var thing = thingToTest.charAt(0);
if (thing = "some random letter that isn't in the code") {
     alert("This should not come up...");
};
然而,不管信是否正确,警报总是会弹出。我已经更新了我所有的软件,重新启动了我的电脑,但它从来没有工作过。我肯定我做错了什么,但我不知道是什么。我花了很多时间想弄明白

使用==或===在JavaScript中执行相等性检查:

var thingToTest = "Some Random String"
var thing = thingToTest.charAt(0);
if (thing === "some random letter that isn't in the code") {
//        ^^^
     alert("This _will not_ come up...");
};
______

在您的示例中,您是在if子句中执行赋值而不是相等检查

赋值计算为其右侧表达式。因此if子句将解析为代码中没有的随机字母,这是真实的。因此,将执行if子句的主体。

=是赋值运算符

例如:

==和===是比较运算符,==只能检查两个变量的值

例如:

但是===可以检查两个变量的值和数据类型

例如:


又是!。事物=。。。因为只有1=分配变量,所以它不会比较它。thing=string应该是thing==string有一个东西叫做字符串验证。谷歌搜索regex
var a = 5;
if(a == 5){
  //success statements 
}
if(a === 5){ // it will check typeof(a) == typeof(RHS value)
  //success statements
}