[英]Why does using '=' in my if statement return undefined?
When I use '=' in my if statement I get undefined, but when I use '===' I get my expected result.当我在 if 语句中使用 '=' 时,我未定义,但是当我使用 '===' 时,我得到了预期的结果。 Can someone explain what's happening there?有人可以解释那里发生了什么吗?
function once(callback) {
let counter = 0;
let result;
function sum(x) {
if (counter === 0) {
result = callback(x);
counter++;
}
return result;
}
return sum;
}
const addByTwoOnce = once(function(num) {
return num + 2;
});
// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(addByTwoOnce(5)); //should log 7
console.log(addByTwoOnce(10)); //should log 7
console.log(addByTwoOnce(9001)); //should log 7
'=' means you are assigning value to the variable. '=' 表示您正在为变量赋值。
if(count = 0)
means count value becomes 0.表示计数值变为 0。
'==' or '===' means checking the value. '==' 或 '===' 表示检查值。
if(count == 0)
checks count is 0 or not.检查计数是否为 0。
if(count === 0) // Strict equality comparison which means checks types also
checks count is 0 and checks both types are also equal or not.检查计数为 0 并检查两种类型是否相等。
=
is Assignment operator =
是赋值运算符
===
is a strict equality comparison operator ===
是严格相等比较运算符
So if you are using =
to your condition, it does assign the value to variable.因此,如果您将=
用于您的条件,它确实会将值分配给变量。
if (counter = 0) { // counter value is 0
result = callback(x);
counter++;
}
This could throw an error in strict mode这可能会在严格模式下引发错误
expected a condition but found an assignment预期有条件但找到了任务
=
is used to set values, and ===
is used to strictly compare values. =
用于设置值,而===
用于严格比较值。
This article has a good explanation of the differences between ==
and ===
: https://bytearcher.com/articles/equality-comparison-operator-javascript/这篇文章很好地解释了==
和===
之间的区别: https : //bytearcher.com/articles/equality-comparison-operator-javascript/
One =
is only used to assign values, eg var x = 2;
一个=
仅用于赋值,例如var x = 2;
Single '=' means you are assigning a RHS value to LHS单个 '=' 表示您正在为 LHS 分配 RHS 值
Double or 3 '===' means you are comparing LHS and RHS Double 或 3 '===' 表示您正在比较 LHS 和 RHS
Please explore more about assignment and comparison operators请探索更多关于赋值和比较运算符的信息
FOR EX:-例如:-
float A = 1 and int B= 1浮点 A = 1 和 int B = 1
if (A==B) //TRUE if (A==B) //真
BUT IF(A===B) //FALSE ,because a and b have different datatypes但是 IF(A===B) //FALSE ,因为 a 和 b 具有不同的数据类型
=
is use for assignment while ==
& ===
is use for comparing two sides =
用于赋值,而==
& ===
用于比较两侧
BONUS:
==
is used to compare the condition if LHS==RHS while ===
not only compares LHS&RHS But also check both LHS AND RHS Should have same data type 'int:int','string:string','float:float' then only comparison between LHS& RHS is Done BONUS:
==
用于比较条件 if LHS==RHS while ===
不仅比较 LHS&RHS 还检查 LHS 和 RHS 应该具有相同的数据类型 'int:int','string:string','float:浮动'然后只有LHS和RHS之间的比较完成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.