单等号如何在javascript中的if语句中工作 [英] How does the single equal sign work in the if statement in javascript

查看:79
本文介绍了单等号如何在javascript中的if语句中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我在互联网上看到了一个可在javascript中工作的语句,我想知道我在if语句中主要使用的javascript中的等号(=)的含义是什么. 这是一个比较函数,其中包含双等号(==)

Recently I saw a statement that works in javascript on the internet and I wonder what the meaning of a single equal sign (=) in javascript as I mostly use in if statements is.
It is a comparison function which include double equal sign (==)

if(i = 1) {
    alert(i);
}

这行得通,我想知道如果if语句被赋值为变量i的值1并检查i的值,该值与以下相同:

This works, I wondered what would happen when the if statement gets assigned to the value of 1 to the variable i and check the value of i which is the same as:

i = 1
if(i) {
    alert(i)
}

但是我很快意识到,值变量的分配需要使用关键字var 所以我将代码更改为:

But I soon realised that the assignation of a value variable needs to have the keyword var so I changed the code to:

  if(var i = 1) {
        alert(i);
  }

这次代码不起作用.为什么?

This time the code doesn't work. Why?

推荐答案

分析的第一部分当然是正确的.

The first part of your analysis is of course correct.

现在,有趣的部分可能是为什么您的最后一个代码if (var ...) {无法正常工作.

Now, the interesting part might be why your last code if (var ...) { doesn't work.

它不起作用,因为

1)

var something

是一个语句,而不是表达式.

2)这是ECMAScript定义 if语句的方式:

2) here's how ECMAScript defines the if statement :

IfStatement:

IfStatement :

if(Expression)语句else语句

if ( Expression ) Statement else Statement

if(Expression)语句

if ( Expression ) Statement

您必须在if子句中放置表达式,而不是语句.

You must put an expression in the if clause, not a statement.

本文中有关表达式vs语句的更多信息.

这篇关于单等号如何在javascript中的if语句中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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