无法读取未定义 javascript 的属性“长度”
2020-03-25
116
我是 javascript 新手,正在做一个项目,需要获取一个数字数组并计算每种数字(正数、负数、零)的数量,然后在另一个数组中返回计数。到目前为止,我尝试了以下代码:
let negatives = 0;
let zeros = 0;
let positives = 0;
function counter(numbersArray = [1, 2, 3, 4, 0, 0, 0, -1, -2]) {
var returnArray = [negatives, zeros, positives]
for (x = 0; x < numbersArray.length; x++) {
if (numbersArray[x] < 0) {
negatives++;
} else if (numbersArray[x] === 0) {
zeros++;
} else {
positives++;
}
}
return returnArray;
}
console.log(counter());
console.log(counter());
console.log(counter());
代码在调用 3 次后返回此值:
counter();
(3) [0, 0, 0]
counter();
(3) [2, 3, 4]
counter();
(3) [4, 6, 8]
我将其调整为:
var numbersArray = [1, 2, 3, 4, 0, 0, 0, -1, -2];
function counter(numbersArray) {
var negatives = 0;
var zeros = 0;
var positives = 0;
var returnArray = [negatives, zeros, positives]
for (x = 0; x < numbersArray.length; x++) {
if (numbersArray[x] < 0) {
negatives++;
} else if (numbersArray[x] === 0) {
zeros++;
} else {
positives++;
}
}
return returnArray;
}
console.log(counter());
console.log(counter());
console.log(counter());
但在调用时出现以下错误:
counter();
VM82:14 Uncaught TypeError: Cannot read property 'length' of undefined
at counter (<anonymous>:14:34)
at <anonymous>:1:1
我理解这意味着我的数组未定义,但我不明白为什么,因为我在第一行定义了它。任何帮助或指导都将不胜感激。
3个回答
错误可能出现在此行
for (x = 0; x < numbersArray.length; x++) {
numbersArray.length
导致此错误,这可能是因为
numbersarray
未初始化。
如果您调用不带参数的
counter
函数,就会发生这种情况。您需要将数组作为参数传递给
counter
函数,如下所示:
counter([1,2,2,3,4,5]);
或者像您的第一个示例一样使用默认值。
Nivas
2020-03-25
您需要重新定位您的 returnArray:
var numbersArray = [1, 2, 3, 4, 0, 0, 0, -1, -2];
function counter(numbersArray) {
var negatives = 0;
var zeros = 0;
var positives = 0;
for (x = 0; x < numbersArray.length; x++) {
if (numbersArray[x] < 0) {
negatives++;
} else if (numbersArray[x] === 0) {
zeros++;
} else {
positives++;
}
}
var returnArray = [negatives, zeros, positives]
return returnArray;
}
console.log(counter(numbersArray));
DCR
2020-03-25
感谢大家的帮助。我将其调整为:
function counter (numbersArray = []){
let negatives = 0;
let zeros = 0;
let positives = 0;
for (x = 0; x < numbersArray.length; x++){
if (numbersArray[x] < 0) {
negatives ++;
} else if (numbersArray[x] === 0){
zeros ++;
} else {
positives++;
}
var returnArray = [negatives, zeros, positives]
}
return returnArray;
}
这允许我在调用函数时根据需要传递参数,例如: counter([1,2,3,0,4,0,0,0,-1,-2]);
thebigrlebowski
2020-03-26