将变量初始化为全局变量与局部变量会产生不同的结果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 

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...