![](/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.