TypeError: 无法读取未定义的属性(读取 ‘length’)。Codewars 任务

huangapple go评论64阅读模式
英文:

TypeError: Cannot read properties of undefined (reading 'length'). Codewars task

问题

我写了解决方案,得到了以下错误信息:TypeError: Cannot read properties of undefined (reading 'length').

这是我的解决方案:

function sumArray(array) {
  if (array === null || array.length < 2) {
    return 0;
  }
  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }
  return sum - Math.max(...array) - Math.min(...array)
}

你能帮我找到代码中的错误吗?

英文:

I write solutions to tasks and got
>TypeError: Cannot read properties of undefined (reading 'length').

This is my solution

function sumArray(array) {
  if (array === null || array.length &lt; 2) {
    return 0;
  }
  let sum = 0;
  for (let i = 0; i &lt; array.length; i++) {
    sum += array[i];
  }
  return sum - Math.max(...array) - Math.min(...array)
}

Could you help me find an error in my code?

答案1

得分: 1

undefinednull 不是 ===。在调用 length 方法之前,你需要同时测试两者,或者不要使用 undefined 作为参数调用该方法。

英文:

undefined is not === with null. You need to test for both before calling length on your argument, or don't call this method with an undefined argument.

答案2

得分: 0

你需要检查数组是否已定义并且它的类型是数组。

我认为你需要在参数数组未定义或为空时返回0。

if (!array || (Array.isArray(array) && array.length < 2)) {
    return 0;
  }
英文:

You need to check is array even defined and that it is type array.

And I think you need to return 0 in all variant where argument array is not defined or null

if (!array || (Array.isArray(array) &amp;&amp; array.length &lt; 2)) {
    return 0;
  }

答案3

得分: 0

根据您提供的代码,错误可能是由于将未定义或空值作为sumArray函数的参数调用而引起的。以下代码已修复:

function sumArray(array) {
  if (!Array.isArray(array) || array.length < 2) {
    return 0;
  }
  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }
  return sum - Math.max(...array) - Math.min(...array);
}
英文:

Based on the code you provided, it's possible that the error is being caused by calling the sumArray function with an undefined or null value as its argument. The code below is fixed.

function sumArray(array) {
  if (!Array.isArray(array) || array.length &lt; 2) {
    return 0;
  }
  let sum = 0;
  for (let i = 0; i &lt; array.length; i++) {
    sum += array[i];
  }
  return sum - Math.max(...array) - Math.min(...array);
}

huangapple
  • 本文由 发表于 2023年2月19日 21:49:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定