그래서 내가 두 개의 데이터가 나는 루프에 대해 동일한 얻으려고하는 상황이있다 (물론 나는 루프에 대한 동일한 나오고 싶지 않다 반복적 인 코드가 있음).두 개의 변수에 대한 같은 루프에 대한 해결
finalFloor에 대한 검색 중입니다. 내 데이터 배열도 나를 필요로합니다. 하지만 주소 []의 어떤 인덱스에서 변수 currentFloor가 음수 값이되는지 찾고 있습니다.
아래 코드는 현재 찾고있는 최종 목표를 제외하고 동일한 코드 (원하지 않는 코드 작성 방식은 아님)를 실행하는 두 개의 별도 함수 (floorCalculator & inTheBasement)로 실행합니다. 나는 이것을 결합하는 방법을 알아 내려고 애쓰는 데 정말 고심하고있다. 어떤 아이디어 또는 포인터? 도와 주셔서 감사합니다! 첫 번째 for
루프에서 currentFloor < 0
에 대한
/* ----------------- Declaration of Variables ---------------- */
var up = '('; // represents moving up 1 floor.
var down = ')'; // represents moving down 1 floor.
var input_form = $('#input-form'); // represents the html input form.
var userInput = input_form.find('#address-input'); // represents the finding of the user's input.
var input; // stores user input value.
var address = []; // stores user's input value as an array of characters.
var currentFloor = 0; // represents the current floor in the for loop, set to ground floor (0).
var finalFloor; // represents the ending floor from the instructions given.
var results = $('.results'); // represents the div .results for appending data to.
/* ----------------- Parent Function ---------------- */
$(document).ready(initLoad);
/* ----------------- Child Functions ---------------- */
function initLoad()
{
input_form.submit(function(event) // Listens for submission event at #input-form.
{
event.preventDefault(); // Prevents default method of html element.
takeInAddress(); // Calls function.
});
};
function takeInAddress()
{
input = userInput.val(); // Stores the user input found at #address-input as var input.
userInput.val(''); // Clears the input field for next user input.
address = input.split(''); // Splits the string input into single characters stored now in the array address[ ].
floorCalculator(); // Calls funciton.
};
function floorCalculator()
{
for (var i = 0; i < address.length; i++)
{
if (address[i] == up) // For any '(' present at the current index...
{
currentFloor++; // Increase the value of currentFloor by 1.
}
else if (address[i] == down) // For any ')' present at the current index...
{
currentFloor--; // Decrease the value of currentFloor by 1.
}
} // end for loop
finalFloor = currentFloor; // Store the value of currentFloor now as finalFloor.
// console.log(finalFloor);
results.append('<h2>Floor to deliver to: ' + finalFloor + '</h2>'); // Append finalFloor value to .results html.
inTheBasement(); // Calls function.
};
function inTheBasement()
{
currentFloor = 0; // Resets currentFloor to zero.
for (var i = 0; i < address.length; i++)
{
if (address[i] == up) // For any '(' present at the current index...
{
currentFloor++; // Increase the value of currentFloor by 1.
}
else if (address[i] == down) // For any ')' present at the current index...
{
currentFloor--; // Decrease the value of currentFloor by 1.
if (currentFloor < 0) // if currentFloor becomes a negative value...
{
// console.log(i);
// Append value of i
results.append('<h2>When you will arrive in the basement: ' + i + 'th instruction. </h2>');
break; // break from loop
} // end if loop
} // end else if loop
} // end for loop
};
예 (바닥에 올랐다가 바닥에 있음) 7000 개의 괄호가있는 문자열입니다. 그래서 문자열을 .split ("")에 전달하여 문자열을 7000 자로 분리하고 배열 주소 []에 저장했습니다. 그런 다음 가장 쉬운 방법은 for 루프를 사용하여 배열을 반복하면서 "up"또는 "down"을 누른 다음 현재 바닥에 +/- 1을 묻는 것입니다. 보낸 코드를 설명해 주시겠습니까? 나는 여전히 JS & jQuery를 처음 사용하고있다. – rockchalkwushock
기쁘게 생각합니다.하지만 우선 : 지금 코드를 이해하고 있다고 생각합니다. 확실하게 할 수 있습니까? 네가 '부정'이라면 '지하실'이 0을 반환하고 그렇지 않으면 아무것도 반환하지 않겠습니까? –
@Cody, 이것이 작동하는지 알려주세요. 답변을 완전히 다시 작성했습니다. 나는 당신의 코드를 이해했다고 믿지만, 당신은 내게 알려야 할 것이다. –