![](/img/trans.png)
[英]How do I use a variable from another function without making the variable global in JavaScript?
[英]How do I return a variable from nested For Loops in JavaScript without using a global variable?
這是我的無輸入代碼
// Check if three addends equal sum and return the product if so
let result;
function addNumbers(first,second,third,sum) {
if (first + second + third === sum) {
result = first * second * third;
return (first * second * third);
}
};
// find three numbers in list that add up to specific number
function testResult(list,sum) {
let firstAddend;
let secondAddend;
let thirdAddend;
for (let i = 0; i < list.length; i++) {
firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
thirdAddend = list[k];
addNumbers(firstAddend,secondAddend,thirdAddend,sum);
}
}
}
};
我想要的是testResult()
在返回產品時從addNumbers()
返回結果。 我想擺脫let result;
和result =...
在addNumbers()
。 我一直對 scope 感到困惑,但我想我開始明白了。 每個for
循環是否包含前一個的scope? 如果有人感興趣,這是來自代碼出現的第 1 天。我不確定這里是否需要數據。 如果是讓我知道,我會相應地編輯。
每個
for
循環是否包含前一個的scope?
是的,它確實。 每當創建子作用域時,前面的 scope 中的所有變量都可用。 因此,您實際上不必提前聲明firstAddend
和secondAddend
和thirdAddend
:
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
addNumbers(firstAddend,secondAddend,thirdAddend,sum);
}
}
}
}
接下來, return
意味着當您調用 function 時,它會采用您返回的值。 因此,您不需要全局result
變量,因為您可以只使用返回值。 但是,您應該將if
語句從addNumbers
function 移到testResult
function 中,因為您需要知道何時返回,而不僅僅是返回什么。 事實上, addNumbers
function 就足夠了,它應該只是 go 直接進入testResult
:
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
if (firstAddend + secondAddend + thirdAddend === sum) {
return firstAddend * secondAddend * thirdAddend;
}
}
}
}
}
作為練習,如果您想要 function,您可以執行以下操作:
function addNumbers(first,second,third,sum) {
if (first + second + third === sum) {
return (first * second * third);
} else {
return null; // return some value so the calling function knows that no sum was found
}
}
function testResult(list,sum) {
for (let i = 0; i < list.length; i++) {
let firstAddend = list.shift();
for (let j = 0; j < list.length; j++) {
let secondAddend = list[j];
for (let k = 1; k < list.length; k++) {
let thirdAddend = list[k];
let result = addNumbers(firstAddend, secondAddend, thirdAddend, sum);
if (result !== null) {
return result;
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.