我需要将一个简单的平面数组“转换”为二维数组,然后我继续查看它对这个论点的看法。
我试图重新创建这个答案的代码,我得到了这个错误:
console.log(array.reduce((twoDArray, n, i) => (i % 3 == 0 ? twoDArray.push([n]) : twoDArray[twoDArray.length-1].push(n)), []));
^
TypeError: Cannot read property 'push' of undefined
问题是我没有&& twoDArray
在箭头函数的末尾添加。在这里你可以看到:
let array = [1,2,3,4,5,6,7,8,9];
// this works
console.log(array.reduce((twoDArray, n, i) => (i % 3 == 0 ? twoDArray.push([n]) : twoDArray[twoDArray.length-1].push(n)) && twoDArray, []));
// here the second push() throws an error
console.log(array.reduce((twoDArray, n, i) => (i % 3 == 0 ? twoDArray.push([n]) : twoDArray[twoDArray.length-1].push(n)), []));
现在我不明白几件事,即:
- 这是如何
&& twoDArray
工作的?它的目的是什么? - 当仅在
push()
生成错误之后放置此添加时,如何修复错误。代码不应该在到达之前抛出错误&&
吗?