所以我有一种情况,我有两个数据,我试图从同一个for循环得到(我希望它来自相同的for循环,没有重复的代码)。
我正在寻找finalFloor,我的数据数据也会带给我;但我也在寻找地址[]中的哪个索引变量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 :(得分:0)
在第一个currentFloor < 0
循环中检查for
。要防止两次打印消息,请使用变量记住是否已经执行过该操作。
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>');
}
};
答案 1 :(得分:0)
因此,您的第一个循环是“reduce”的经典用例:它将数组转换为单个值。
reduce接受一个函数和一个可选的基值:
[1,2,1,1].reduce(aFunction, startValue)
我们将编写一个函数,当传递给reduce时,将一个数组的所有值加在一起。我们传递给reduce的函数应该接受两个值 - 一个'memo',它将在函数调用之间存储状态,并在它们之间传递,一个'value'将代表数组中的下一个值,逐个传递。它应该在将值考虑之后返回状态,并且无论它返回什么,它将在下一次调用时再次传递给函数,以及数组中的下一个值。
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;
}
}
最后,如果我们想要在一个reduce调用中执行此操作,我们只需要在备忘录中传递更多状态,并进行另一次评估。
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
是否为"("
,在地板上添加或减少。 然后我们添加:
output += ("result = " + result.floor);
if (result.basementTrigger) output += ("follow instruction: " + result.becameNegative)
希望这有助于解决问题。
免责声明:没有校对或测试代码,可能会出错;我的目标不是为你提供代码,而是为了向你展示概念。这是一个快速抛出的hacky渲染,但应该说明你可以自己使用的工具。