【问题标题】:TypeError: Cannot read property 'length' of null, how can i solve it?TypeError:无法读取 null 的属性“长度”,我该如何解决?
【发布时间】:2021-09-28 09:50:48
【问题描述】:

我仍在学习 javascript,为了练习,我在 codewars.com 上进行了一系列练习,但其中一个遇到了问题。 请求如下: 给定一个整数数组。

返回一个数组,其中第一个元素是正数的计数,第二个元素是负数的总和。

如果输入数组为空或null,则返回一个空数组。

对于输入 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15],您应该返回 [10, -65 ].

我制定了以下适用于所有情况的算法:

function countPositivesSumNegatives(input) {
  var arrOutput = []; //declare the final array
  var pos = 0; //declare the positive 
  var neg = 0; //declare the negative
  var check, ss;

  for (var x = 0; x < input.length; x++){
    if(input[x]>0){ pos++; }
    else{ neg = neg + input[x] ; }
    arrOutput = [pos, neg]
  }
  
  return arrOutput;
}

但它返回了以下错误:

TypeError: Cannot read property 'length' of null
    at countPositivesSumNegatives (test.js:8:29)
    at Context.<anonymous> (test.js:39:18)
    at processImmediate (internal/timers.js:461:21)

由于这个错误,我无法通过测试。 我该如何解决它,为什么它会给我这个错误?

【问题讨论】:

  • If the input array is empty or null, return an empty array. 并不总是传递给你一个数组,有时你也会传递给null。如果input 为空,则input.length 不起作用。您需要检查代码中某处的null
  • 之前的评论说得对。只需添加对 null 的检查: if (input === null) ... 您还想将 arrOutput = [pos, neg] 移到循环之外,否则每次迭代只是覆盖相同的变量。

标签: javascript arrays list algorithm


【解决方案1】:

所以如果我们调用你的函数,输入等于 null / undefined:

function countPositivesSumNegatives(input) { // input = null
  var arrOutput = []; // OK
  var pos = 0; //OK 
  var neg = 0; //OK
  var check, ss; // OK

  for (var x = 0; x < input.length; x++){ // error is here
  ...

在 JS 中,null 被定义为:“表示有意不存在任何对象值的原始值”

所以当你尝试访问null的成员时,JS会因为null没有成员而抛出错误。

您有一个要检查的变量,但您应该为该检查编写代码以查看输入是否等于您提到的任何非法值。

一个简单的蛮力解决方案是检查输入是否等于任何非法值。例如

if (input === null || input === undefined || input === []) return []

for 循环之前。

【讨论】:

    【解决方案2】:

    尝试在“for”循环中使用“input?.length”。

    “输入”没有“长度”属性,因此您会收到错误。

    function countPositivesSumNegatives(input) {
      var arrOutput = []; 
      var pos = 0;  
      var neg = 0; 
      var check, ss;
        
      for (var x = 0; x < input?.length; x++){
        if(input[x]>0){ pos++; }
        else{ neg = neg + input[x] ; }
        arrOutput = [pos, neg]
      }
          
      return arrOutput;
    }
    

    【讨论】:

    • 这更像是一条评论。
    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多