简体   繁体   English

将此参数和第二个参数传递给回调函数

[英]pass this and second parameter to callback function

I have a JSCS rule that identifies functions within for loops. 我有一个JSCS规则,用于标识for循环内的函数。 I'm wanting to adhere to the rule vs turn off the warning. 我要遵守规则vs关闭警告。 This is the code in the JSCS error state. 这是处于JSCS错误状态的代码。

let sum = 0;
for (var key in denomGroup) {
    denomGroup[key].forEach(function (denom) {
        sum = addToSum(sum, denom)
    });
}
return sum;

I've tried this below and the addToSum function gets the object, but I can't figure out how to pass in the sum and have it iterate and continue to add other values 我已经在下面尝试过了, addToSum函数获取了对象,但是我无法弄清楚如何传递总和并进行迭代并继续添加其他值

for (var key in denomGroup) {
    denomGroup[key].forEach(addToSum);
} 

function addToSum(denom, sum) { //denom has object, sum is empty
    return sum += denom.sum;
}

I've also tried 我也尝试过

for (var key in denomGroup) {
    denomGroup[key].forEach(addToSum(sum));
} 

function addToSum(sum, denom) { //sum has 0, denom is empty
    return sum += denom.sum;
}

How can I correctly call an outside function with the intent of the first code block? 我如何正确地调用第一个代码块的意图来调用外部函数? I need to avoid just placing sum as a global variable. 我需要避免仅将sum作为全局变量。

You don't need to pass the sum to the function, simply declare the function within the same scope as you declare sum : 您无需将sum传递给函数,只需在声明sum的相同范围内声明函数:

 let sum = 0; let denomGroup = { a: [1,2,3], b: [4,5,6] }; function addToSum(denom) { return sum += denom; } for (var key in denomGroup) { denomGroup[key].forEach(addToSum); } console.log(sum); 

EDIT: as @ScottMarcus points out, the sum variable doesn't need to be global, just in the same (or a higher) scope as the function definition. 编辑:正如@ScottMarcus指出的, sum变量不需要是全局变量,只需在与函数定义相同(或更高)的范围内即可。 You could, for example, encapsulate the whole thing as so: 例如,您可以这样封装整个内容:

 function countDenoms(denomGroup) { let sum = 0; function addToSum(denom) { sum += denom; } for (var key in denomGroup) { denomGroup[key].forEach(addToSum); } return sum } console.log(countDenoms({ a: [1, 2, 3], b: [4, 5, 6] })); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM