英文:
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 < 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)
}
Could you help me find an error in my code?
答案1
得分: 1
undefined
与 null
不是 ===
。在调用 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) && array.length < 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 < 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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论