简体   繁体   English

JavaScript if语句表现不正常

[英]JavaScript if statement not behaving as expected

Just learning to code JavaScript, trying to learn if statements but my code isn't working: 只是学习编码JavaScript,试图了解语句但我的代码不起作用:

var car = 8;
if (car = 9) {
    document.write("your code is not working")
}

This executes the write command and I have no idea why. 这执行写命令,我不知道为什么。 I'm using the tab button for indents, is that not allowed? 我正在使用选项卡按钮缩进,这是不允许的吗?

= is called assignment operator in JavaScript, it assigns the value of the right hand side expression to the variable on the left hand side. =在JavaScript中称为赋值运算符,它将右侧表达式的值分配给左侧的变量。

You have to use comparison operator instead of assignment operator like this 您必须使用比较运算符而不是像这样的赋值运算符

if (car === 9)

We have two comparison operators in JavaScript, == and === . 我们在JavaScript中有两个比较运算符===== The difference between them is that, 他们之间的区别是,

== checks if the values are the same, but === checks if the type and the value is also the same. ==检查值是否相同,但===检查类型和值是否也相同。

Go through the wonderful answers, to know more about == and === 浏览精彩的答案,以了解有关==和===的更多信息

This line assigns car to the value of 9 and check if it is truthy (which 9 is). 该行将car赋值为9,并检查它是否为真(9为真)。

if (car=9)

I think you want to use a comparison operator, like this: 我认为您想使用比较运算符,如下所示:

if(car == 9)

use this code 使用此代码

var car = 8;
if (car==9)
  {
  document.write("your code is not working")
  }

you need to understand about operators '=' is an assignment operator whereas '==' is a comparision operator. 您需要了解运算符'='是赋值运算符,而'=='是比较运算符。

See Tutorial 参见教程

If you want to compare if car is equal to 9, then you have to use code 如果要比较car是否等于9,则必须使用代码

    if(car === 9){
      /*Your code goes here*/
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM