如果(a = 1)为真 [英] if(a = 1) is true

查看:55
本文介绍了如果(a = 1)为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否可能重复.测试我的代码,有时我错了,因为我在条件中输入了 = 而不是 == ===

I don't know if it's possible duplicate. Testing my code, sometimes I was wrong with because I put = and not == or === in if conditions:

考虑以下代码:

var a = 0;
if(a = 1) console.log('true'); 

我不知道为什么这不是错误,为什么返回true条件(a = 1)我想这是将 1 分配给 a 变量,但是为什么它的计算结果为true并且没有错误?

I don't know why this is not an error and why returns true the condition (a = 1) I guess that what it does is assign 1 to the a variable, but why this evaluates to true and there's no error?

推荐答案

您要将a设置为1,然后检查结果的真实性.JavaScript中的非零数字是真实的,因此您得到的是所见即所得.

you're setting a to 1 and then checking the truthiness of the result. Non-zero numbers in JavaScript are true, so you get what you see.

就像数学一样,事物从左到右进行评估,首先是括号.

Like in math, things are evaluated left-to-right, with parens going first.

这篇关于如果(a = 1)为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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