2.4 KiB
2.4 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7b85367417b2b2512b38 | Catch Use of Assignment Operator Instead of Equality Operator | 1 | 捕获使用赋值运算符而不是等式运算符 |
Description
if
, else if
和else
语句。条件有时采取测试结果是否等于值的形式。这种逻辑(至少在英语中)是“如果x等于y,则......”,它可以使用=
或赋值运算符逐字地转换为代码。这会导致程序中出现意外的控制流。如前面的挑战所述,JavaScript中的赋值运算符( =
)为变量名赋值。并且==
和===
运算符检查相等性(严格相等的三重===
测试,意味着值和类型都相同)。下面的代码将x
指定为2,其值为true
。几乎JavaScript中的每个值都评估为true
,除了所谓的“falsy”值: false
, 0
, ""
(空字符串), NaN
, undefined
和null
。 设x = 1;
让y = 2;
if(x = y){
//此代码块将针对y的任何值运行(除非y最初设置为假)
} else {
//这个代码块是本例中应该运行的(但不会)
}
Instructions
result
分配适当的值。 Tests
tests:
- text: 您的代码应该修复条件,以便检查是否相等,而不是使用赋值。
testString: 'assert(result == "Not equal!", "Your code should fix the condition so it checks for equality, instead of using assignment.");'
- text: 条件可以使用<code>==</code>或<code>===</code>来测试相等性。
testString: 'assert(code.match(/x\s*?===?\s*?y/g), "The condition can use either <code>==</code> or <code>===</code> to test for equality.");'
Challenge Seed
let x = 7;
let y = 9;
let result = "to come";
if(x = y) {
result = "Equal!";
} else {
result = "Not equal!";
}
console.log(result);
Solution
// solution required