【问题标题】:Returning Null - why is this going wrong?返回 Null - 为什么会出错?
【发布时间】:2022-01-15 07:47:06
【问题描述】:

我用这段代码返回 null,但是我看不出为什么/哪里出错了。 (这可能是由于排序功能,因为我从一个备受好评的 sn-p 关于如何对数组进行排序得到了这个)。比起正确答案,我更在乎理解。

我想要完成的任务:

Ratiorg 从 CodeMaster 那里得到了不同尺寸的雕像作为生日礼物,每个雕像都有一个非负整数大小。因为他喜欢把事情做得完美,所以他想把它们从小到大排列,这样每个雕像都会比前一个大一倍。他可能需要一些额外的雕像才能做到这一点。帮助他找出所需的最少额外雕像数量。

例子

对于statues = [6, 2, 3, 8],输出应该是 solution(statues) = 3.

Ratiorg 需要尺寸为 4、5 和 7 的雕像。

我的代码和想法:

function solution(statues) {

  let total = 0;

  statues.sort(function(a, b) { //From what I understand this should sort the array numerically 
    return a - b;
  });

  for (let i = 1; i < statues.length; i++) { //iterate through the array comparing the index to the one before it
    if (statues[i + 1] != (statues[i] + 1)) { //if there is a diff between index of more than 1 it will add the diff 
      total += statues[i + 1] - statues[i]; //to the total variable 
    }
  }
  return total;

}

const result = solution([6, 2, 3, 8]);
console.log(result);

【问题讨论】:

  • i == statues.length - 1 statues[i + 1] 返回undefined,然后将其添加到total 得到结果NaN
  • 为什么忽略第一个元素(let i = 1;)?
  • 为什么说它返回的是null,而实际上它返回的是NaN
  • 既然你是从1开始的,我想你应该和statues[i-1]比较,而不是statues[i+1]

标签: javascript null


【解决方案1】:

感谢评论的人帮助我看到我的逻辑中存在一些错误 - 我现在更改了 if 语句以比较从 1 开始的索引与其后面的索引,即索引 1 与索引 0 的比较。也就是说,以下行有问题 total += statues[i] - statues[i-1]; 我用 for 循环替换了它,这样它就可以计算到数字而不是简单的减法。


 function solution(statues) {
        //[6, 2, 3, 8] --- 2,3,6,8  --- 3,6 7-2, 
        let total = 0;
        
        statues.sort(function(a, b) {                  
            return a - b;
                });
       
        for(let i =1; i<statues.length; i++){         
            if(statues[i] != (statues[i-1]+1) ){       
                //total += statues[i] - statues[i-1];    
                for(let j = statues[i-1]; j<statues[i]-1; j++){
                    total += 1;
                }
                 } 
                 
        }
        return total;
        
    }

【讨论】:

    猜你喜欢
    • 2013-08-09
    • 2013-06-05
    • 2014-05-23
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多