我目前正在节点中编写一个程序,代码的一部分如下所示:
function interpretRange(num, shorthand) {
let shorthandLength = shorthand.length
console.log(typeof num);
console.log(num.length);
...当我运行这段代码时,将'1'作为num的参数传递,在我的控制台中可以看到以下内容:
string
1
undefined
/Users/username/Documents/10. Programming/problem 4.js:78
console.log(num.length);
^
TypeError: Cannot read property 'length' of undefined知道为什么会发生这个错误吗?如您所见,我检查了num的类型,它是一个字符串。然后,当我将num打印到控制台时,它工作并打印1,这是正确的。
但是,由于某些原因,我仍然得到类型错误(即使在将值打印到控制台之后)。
编辑:完整代码在这里:
错误发生在num.length
function completeNumbers(shorthand) {
let ranges = shorthand.split(', ');
let longHand = [];
ranges.forEach(range => {
let interpreted = [];
let expanded = [];
range.split(/[-:..]/g)
.reduce((curr, shorthand) => { // What hapens if it's one number
interpreted.push([curr, interpretRange(curr, shorthand)])
})
console.log(interpreted);
interpreted.forEach(range => expanded.push(expandList(range)))
console.log(expanded)
})
}
function interpretRange(num, shorthand) {
let shorthandLength = shorthand.length
let baseNum = num.length === shorthand.length ? '0' : num.slice(0, -shorthandLength)
let compareNum = num.slice(-shorthandLength);
if (parseInt(shorthand) <= parseInt(compareNum)) {
return String(parseInt(baseNum) + 1) + shorthand;
} else {
return baseNum + shorthand;
}
};
completeNumbers("1:5:2, 3"); // 1, 2, 3, 4, 5, 6, ... 12发布于 2021-12-07 01:00:02
问题是,您不返回任何来自约简,所以第二次迭代将有undefined作为previousValue的约简函数。这就是你看到这个错误的原因(看看约简函数的文档)
我不知道您实际上想要做什么,但是您必须在减缩函数中返回一些内容(根据您想要做的事情),或者考虑使用map或简单地使用一个经典的for循环
https://stackoverflow.com/questions/70253431
复制相似问题