Javascript difference between "=" and "==="
This question already has an answer here:
You need to use == or === for equality checking. = is the assignment operator.
You can read about assignment operators here on MDN.
I assume you know that = is for assignment, after all, you are using assignment already in the first line:
var testTest = function(answer) {
and I don't think you think that this would compare anything here (or do you?).
The question remains though, why does = in if (answer = "doggies") "not work"?
An assignment is an expression. The result of that expression is the value that was assigned. Here, the result of answer = "doggies" is "doggies" , ie you essentially running if ("doggies") .
JavaScript performs type coercion . That means it automatically converts values of one data type to values of a different data type if necessary, according to specific rules.
The condition of an if statement has to resolve to a Boolean value. But here you are using a string value as condition. The String -> Boolean conversion rules are pretty simple:
false . true . So, after type conversion, the statement is equivalent to if (true) , hence it will always execute the first block, never the else block.
作为您学习JS的快速参考:
= assignment operator
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
链接地址: http://www.djcxy.com/p/19442.html
上一篇: Javascript如果其他速记
