我在 JS 中有這段代碼
//param A : array of integers
//param B : array of integers
//return an integer
function doesitwork(A, B) {
if (A.length != B.length) {
return -1;
}
var i = 0;
var tank;
var count;
var johnny = true;
for (var j = 0; j < A.length; j ) {
count = 0;
tank = 0;
i = j;
johnny = true;
while (count < A.length && johnny == true) {
console.log(i);
console.log(A.length);
console.log(count);
console.log(johnny);
tank = A[i];
if (B[i] <= tank)
tank -= B[i];
else {
johnny = false;
}
count ;
i ;
if (i == A.length)
i == 0;
}
while (johnny == true) {
if (count == A.length)
return j;
}
}
return -1;
}
var A = [1, 2];
var B = [2, 1];
console.log(doesitwork(A, B));
我不明白的是當我運行程式時,首先count = 0,但是當我第一次進入while回圈時,不是運行命令count 并將其值更改為1,而是不運行它, 保持 count 為 0,然后在重新進入回圈后更改它。
TLDR:While 回圈運行兩次,其中一個變數保持相同的值,而不是像回圈中的一行建議的那樣更改它。
uj5u.com熱心網友回復:
不清楚你想做什么,但while回圈的條件并不總是正確的,這使得回圈count= 0內部for。所以,你需要把var count =0;
//param A : array of integers
//param B : array of integers
//return an integer
function doesitwork(A, B) {
if (A.length != B.length) {
return -1;
}
var i = 0;
var tank;
var count=0;
var johnny = true;
for (var j = 0; j < A.length; j ) {
tank = 0;
i = j;
johnny = true;
while (count < A.length && johnny == true) {
console.log(i);
console.log(A.length);
console.log(count);
console.log(johnny);
tank = A[i];
if (B[i] <= tank)
tank -= B[i];
else {
johnny = false;
}
count ;
i ;
if (i == A.length)
i == 0;
}
while (johnny == true) {
if (count == A.length)
return j;
}
}
return -1;
}
var A = [1, 2];
var B = [2, 1];
console.log(doesitwork(A, B));
uj5u.com熱心網友回復:
TLDR:While 回圈運行兩次,其中一個變數保持相同的值,而不是像回圈中的一行建議的那樣更改它。
您假設count從未增加過,因為您假設while回圈繼續第二次。實際上,while回圈在單次迭代后退出,并且for回圈重置count為0。然后while再次進入回圈,但具有不同的值j。
細節
第一次通過您的while回圈,B[i]is2和A[i]is 1。tank = A[i]maketank的值為1。因此,b[i] <= tank是false,所以您設定johnny為false。這意味著在該迭代結束時,您的while條件 ( ... && johnny == true) 為false,因此您不會while再次繼續回圈。
相反,控制移出到for回圈,回圈重置count為0。
為了將來除錯此類問題,學習使用除錯器會有所幫助:您可以在您想要的位置放置斷點,并在您逐步執行時查看控制流如何以及變數如何變化。如果您發現這是不可能的,您可能需要更詳細地記錄日志,如下所示。
//param A : array of integers
//param B : array of integers
//return an integer
function doesitwork(A, B) {
if (A.length != B.length) {
return -1;
}
var i = 0;
var tank;
var count;
var johnny = true;
for (var j = 0; j < A.length; j ) {
console.log("entering for loop");
count = 0;
tank = 0;
i = j;
johnny = true;
while (count < A.length && johnny == true) {
console.log("entering while loop");
console.log("i", i);
console.log("j", j);
console.log("A.length", A.length);
console.log("count", count);
console.log("johnny", johnny);
tank = A[i];
if (B[i] <= tank)
tank -= B[i];
else {
console.log(B[i], tank, "setting johnny to false");
johnny = false;
}
count ;
i ;
if (i == A.length)
i == 0;
}
while (johnny == true) {
if (count == A.length)
return j;
}
}
return -1;
}
var A = [1, 2];
var B = [2, 1];
console.log(doesitwork(A, B));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315462.html
標籤:javascript 循环 while 循环
下一篇:如何在回傳之前等待回圈中的承諾?
