将变量初始化为全局变量与局部变量会产生不同的结果JavaScript

问题描述

我有一个关于将变量初始化为全局变量与局部变量的问题。对于辅助函数dfs中的变量sum作为全局变量输出:16)与sum作为局部变量,我得到了不同的结果。它与递归性质有关吗?

我正在计算总和,即每个整数的总和乘以其在嵌套数组中的深度。

测试用例为[[1,1],2,[1,1]] 总和的正确答案是10。

在这种情况下,为什么第一个方法声明一个全局变量错误的?最佳做法是什么?

//global variable 

let sum = 0
function dfs(nestedList,depth){
    
    for(let i=0; i<nestedList.length; i++){
        if(nestedList[i].isInteger()) {
            sum += nestedList[i].getInteger()*depth
        }
        else {
           sum += dfs(nestedList[i].getList(),depth+1)
        }
    }
   return sum
    
}

var depthSum = function(nestedList) {
    console.log(sum)
    return dfs(nestedList,1)
};
local variable


function dfs(nestedList,depth){
    let sum = 0
    for(let i=0; i<nestedList.length; i++){
        if(nestedList[i].isInteger()) {
            sum += nestedList[i].getInteger()*depth
        }
        else {
           sum += dfs(nestedList[i].getList(),1)
};

解决方法

递归是一种功能性遗产,因此将其与功能性样式一起使用通常会产生最佳效果。下面我们将dfs视为一个纯表达式。对全局范围,中间状态和副作用的担忧消失了!

const dfs = (t = [],d = 0) =>
  Array.isArray(t)
    ? t.reduce((r,v) => r + dfs(v,d + 1),0)
    : t * d
    
console.log(dfs([[1,1],2,[1,1]]))
// (1*2 + 1*2 + 2*1 + 1*2 + 1*2)
// 10 

console.log(dfs([1,[2,[3,[4]]]]))
// (1*1 + 2*2 + 3*3 + 4*4)
// 30