2016-08-22 28 views
0

所以我有一個情況,我有兩塊數據我試圖從相同的循環(以及我希望它出來的相同的循環不有重複的代碼)。解決兩個變量在相同的循環

我正在尋找finalFloor我的數據數組也將帶我;但我也在尋找address []中的哪個索引變量currentFloor成爲負值。

下面是我的代碼,目前我運行這兩個獨立的函數(floorCalculator & inTheBasement),運行相同的代碼(不想要的,不好的編碼實踐),除了最終目標是什麼被發現。我非常努力想弄清楚如何結合這一點。任何想法或指針?謝謝您的幫助!

/* ----------------- 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 
    }; 

回答

0

因此,您的第一個循環是「reduce」的經典用例:它將數組轉換爲單個值。

減少需要的功能,以及可選的基值:

[1,2,1,1].reduce(aFunction, startValue) 

我們要編寫一個函數是,通過減少時,增加了一個數組的所有值加在一起。我們傳入reduce的函數應該接受兩個值 - 一個將在函數調用之間存儲狀態並在它們之間傳遞的「備忘錄」,以及一個「值」,它將表示數組中的下一個值,逐個傳遞。它應該返回狀態之後的任何狀態,並且任何返回的狀態都將在下一次調用中再次傳遞到函數中,以及數組中的下一個值。

function aFunction(value, memo) { 
    return value + memo; 
} 
startValue = 0; // we start with 0 for our use case 

我們可以讓函數語法短,像這樣:

(memo, value) => value + memo 
// the return statement is implicit in this syntax 

其結果是,通過我們的功能,我們開始值變成一個班輪:

[1,2,1,1].reduce((memo, value) => value + memo, 0) 

唯一其他知識點是三元的:

(memo, value) => value === ")" ? memo + 1 : memo - 1 

上面的等價於:

function (memo, value) { 
    if (value === ")") { 
     return memo + 1; 
    } 
    else { 
     return memo - 1; 
    } 
} 

最後,如果我們想要做到這一切在一個電話減少,我們只需要通過多一點的狀態一起在我們的備忘錄,做一套評價。

ourInput = ")()()((())))))()()()(".split(""); 
// it's now an array, as you know 
state = { floor: 0, basementTrigger: false, becameNegative: undefined }; 
result = ourInput.reduce((memo, value, index) => { 
    memo.floor += value === "(" ? 1 : -1; // add either 1 or negative one to our floor 
    if (!memo.basementTrigger && memo.floor < 0) { 
     memo.becameNegative = index 
     memo.basementTrigger = true; 
    } 
    return memo; 
}, state) // state is passed in as 'memo' on the inner functions's first call 

對於每一個值,此:

  • 或者添加或從地板中減去,根據value是否"("
  • 如果觸發是假的,地板是負的,它:
    • 翻轉觸發爲true,並存儲當前指數

那麼我們只需要添加:

output += ("result = " + result.floor); 
if (result.basementTrigger) output += ("follow instruction: " + result.becameNegative) 

希望這可以幫助您解決問題。

免責聲明:沒有校對或測試代碼,可能是錯誤;我的目標不是反正給你編碼,而是向你展示概念。這是一個快速渲染的黑客渲染,但應該說明你可以自己使用的工具。

+0

是的,它是一串7000個圓括號,其中(在地板上)落在地板上。所以我把字符串傳入.split(「」)將字符串拆分爲7000個字符並將它們存儲在數組地址[]中。然後想出最簡單的方法是使用for循環遍歷數組,同時詢問「up」或者「down」,然後在我當前的樓層上+/- 1。你能解釋一下你發送的代碼嗎?我對JS和jQuery仍然很陌生。 – rockchalkwushock

+0

很高興,但首先:我認爲我現在瞭解你的代碼 - 你能澄清一下以確定嗎?你想'地下室'返回0如果它是否定的,並且不返回任何其他的東西? –

+0

@Cody,讓我知道這是否工作。完全重寫了答案。我相信我瞭解你的代碼,但你必須讓我知道。 –

0

在第一個for循環中檢查currentFloor < 0。要避免兩次打印該消息,請使用變量來記住是否已經完成。

function floorCalculator() 
{ 
    var foundBasement = false; 
    var basementStep; 
    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 && !foundBasement) { 
     foundBasement = true; 
     basementStep = i; 
    } 
    } 
    } // 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. 
    if (foundBasement) { 
    results.append('<h2>When you will arrive in the basement: ' + basementStep + 'th instruction. </h2>'); 
    } 
}; 
+0

謝謝!我覺得如果聲明是正確的,將當前地址<0放入else中;但如果不迭代currentFloor的每個負面實例,都找不到解決此問題的方法。我非常感謝幫助,並會記下這一策略! – rockchalkwushock

相關問題