JavaScript:使用公共方法和私有方法的数组之和

瑙曼·坦维尔

我正在尝试使用公共方法添加数组的数字,在该方法中我将传递数组和一个将进行添加的私有方法。公共方法将使用私有方法进行计算。

以下是我尝试过的

这段代码做加法,但我通过相同的阵列,即两次publicMethod,并privateMethod和它只是看起来是多余的。

let arr = [1, 2, 3, 4, 5, 6, 7];

function publicMethod(arr) {
  //console.log(arr);
  var total = 0;

  function privateMethod(...numbers) {
    console.log('inner');
    for (const number of numbers) {
      console.log('num', number);
      total += number;
      console.log('total', total);
    }
    return total;
  }
  return privateMethod(...arr);
}
// console.log(arr);
console.log(publicMethod(arr));
console.dir(publicMethod);

舒巴姆·哈特里

您不需要将相同的数组传递给 privateMethod,因为它会在初始化时从其封闭的闭包中获取值。您只需要传递未在封闭闭包中定义的任何其他变量

let arr = [1, 2, 3, 4, 5, 6, 7];

function publicMethod(arr) {
  //console.log(arr);
  var total = 0;

  function privateMethod() {
    console.log('inner');
    for (const number of arr) {
      console.log('num', number);
      total += number;
      console.log('total', total);
    }
    return total;
  }
  return privateMethod;
}
// console.log(arr);
console.log(publicMethod(arr)());
console.dir(publicMethod(arr));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章