[英]Array.reduce strange behaviour
Hello everyone ! 大家好 !
I'm currently working to get a user input and parse it my way. 我目前正在努力获取用户输入并以我的方式对其进行解析。 The input represents integer ranges or single integers. 输入代表整数范围或单个整数。 Let's say I get the following ranges array : 假设我得到以下range数组:
const ranges = [`1-6`, `8`, `12-20-18`, `22-21`, `46-42-44`];
Now I need a complete integer list so I wrote this chunk : 现在我需要一个完整的整数列表,所以我写了这个块:
const list = ranges.reduce ((array, range) => {
console.log (array);
if (!range.incldues (`-`)) return array.push (parseInt (range)); // Single integer
const milestones = range.split (`-`).map (milestone => parseInt (milestone)),
min = Math.min (...milestones),
max = Math.max (...milestones);
for (let i = min; i <= max; i++) array.push (i);
console.log (array);
return array;
}, []);
The thing is I quicly got a "Uncaught TypeError: array.push is not a function" and console.logging my variables showed that after the first reduce iteration, array took the value (int) 7, despite being an array just before the return statement. 事情是我突然得到了一个“ Uncaught TypeError:array.push不是一个函数”,console.logging我的变量显示,在第一次reduce迭代之后,array的值是(int)7,尽管在返回之前是一个数组声明。
Here is an illustration of it 这是一个说明
Could someone point out where it went wrong ? 有人可以指出哪里出了问题吗? How to prevent it doing so ? 如何预防呢? And furthermore, if someone could explain WHY it went wrong, it would be perfect. 而且,如果有人可以解释为什么会出错,那将是完美的。
Thanks ! 谢谢 !
Two issues: 两个问题:
.includes
(not incldues
) 方法名称为.includes
(不incldues
) Array.prototype.push
returns the new length of the array, not the array itself. Array.prototype.push
返回数组的新长度 ,而不是数组本身。 Use push
first, then use return array
on the next line. 首先使用push
,然后在下一行使用return array
。 Fix those, and it works as expected: 修复这些问题,它可以按预期工作:
const ranges = [`1-6`, `8`, `12-20-18`, `22-21`, `46-42-44`]; const list = ranges.reduce((array, range) => { if (!range.includes(`-`)) { array.push(parseInt(range)); // Single integer return array; } const milestones = range.split(`-`).map(Number), min = Math.min(...milestones), max = Math.max(...milestones); for (let i = min; i <= max; i++) array.push(i); return array; }, []); console.log(list);
Note that because the Number
function converts a non-number to a number, you can simply pass it to .map
rather than using .map (milestone => parseInt (milestone))
(which is a bit wordy). 请注意,由于Number
函数将非数字转换为数字,因此您可以简单地将其传递给.map
而不是使用.map (milestone => parseInt (milestone))
(有点罗y)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.