为什么我的代码只输出 "opened" 而不是 "closed"?
Why is my code outputting only "opened" and not "closed"?
这是一个 100 门 Rosseta 代码挑战。我一直在想为什么输出都是"opened"。我不明白为什么,因为当我经历循环时,它在逻辑上是有道理的。
function getFinalOpenedDoors(numDoors) {
// Good luck!
const DOOR_ARR = [];
const FINALDOOR_ARR = [];
for(let i = 1; i <= numDoors; i++){
DOOR_ARR.push("D" + i);
//DOOR_ARR[i - 1] = "D" + i + " is closed";
DOOR_ARR[i - 1] = "closed";
}
for(let j = 1; j <= numDoors; j ++){
for(let n = 1; n <= numDoors / j; n ++){
if(DOOR_ARR[(n * j) - 1] = "closed"){
DOOR_ARR[(n * j) - 1] = "opened";
}
else{
DOOR_ARR[(n * j) - 1] = "closed";
}
}
/*DOOR_ARR[(n * j) - 1] = "D" + DOOR_ARR[(n * j) - 1] + " is closed" ? "D" + DOOR_ARR[(n * j) - 1] + " is opened" : "D" + DOOR_ARR[(n * j) - 1] + " is closed";*/
}
return DOOR_ARR;
}
您可能想在 if 语句中使用 ==
:
if(DOOR_ARR[(n * j) - 1] == "closed"){
抱歉,我没有权限添加评论。
在 if
语句中使用赋值运算符 =
而不是比较 ===
.
if(DOOR_ARR[(n * j) - 1] = "closed"){
应该是
if(DOOR_ARR[(n * j) - 1] === "closed"){
这是一个 100 门 Rosseta 代码挑战。我一直在想为什么输出都是"opened"。我不明白为什么,因为当我经历循环时,它在逻辑上是有道理的。
function getFinalOpenedDoors(numDoors) {
// Good luck!
const DOOR_ARR = [];
const FINALDOOR_ARR = [];
for(let i = 1; i <= numDoors; i++){
DOOR_ARR.push("D" + i);
//DOOR_ARR[i - 1] = "D" + i + " is closed";
DOOR_ARR[i - 1] = "closed";
}
for(let j = 1; j <= numDoors; j ++){
for(let n = 1; n <= numDoors / j; n ++){
if(DOOR_ARR[(n * j) - 1] = "closed"){
DOOR_ARR[(n * j) - 1] = "opened";
}
else{
DOOR_ARR[(n * j) - 1] = "closed";
}
}
/*DOOR_ARR[(n * j) - 1] = "D" + DOOR_ARR[(n * j) - 1] + " is closed" ? "D" + DOOR_ARR[(n * j) - 1] + " is opened" : "D" + DOOR_ARR[(n * j) - 1] + " is closed";*/
}
return DOOR_ARR;
}
您可能想在 if 语句中使用 ==
:
if(DOOR_ARR[(n * j) - 1] == "closed"){
抱歉,我没有权限添加评论。
在 if
语句中使用赋值运算符 =
而不是比较 ===
.
if(DOOR_ARR[(n * j) - 1] = "closed"){
应该是
if(DOOR_ARR[(n * j) - 1] === "closed"){