为什么数组在reduce中不可迭代

我想按偶数和奇数元素拆分数组,这是我的代码

A.reduce((a,v,i)=> v % 2 == 0 ? [...a[0],v] : [...a[1],v],[[],[]])

A是数字数组。我不明白为什么会出现错误

a [1]是不可迭代的吗?

考虑到此代码可以正常工作:


let arr = [[],[]]; 
console.log([...arr[1], 4]);


慕慕森
浏览 218回答 3
3回答

慕码人2483693

您只在中返回一个数组reduce()。您还需要返回第二个。在第一次迭代中,ais [[],[]]。但是在第一个之后,它将仅成为单个阵列。let A = [1,2,3,4]const res= A.reduce((a,v,i)=> v % 2 == 0 ? [a[0],[...a[1],v]] : [[...a[0],v],a[1]],[[],[]])console.log(res)您可以在此处使用技巧。由于v % 2将返回1或者0所以你可以push()到和使用,返回原来的a不扩散运营商。let A = [1,2,3,4]const res= A.reduce((a,v,i)=> (a[v % 2].push(v),a),[[],[]])console.log(res)

慕田峪7331174

您可以使用解构分配来简化此操作-const data =&nbsp; [ 1, 2, 3, 4 ]const result =&nbsp; data.reduce&nbsp; &nbsp; ( ([ odd, even ], v) =>&nbsp; &nbsp; &nbsp; &nbsp; Boolean (v & 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? [ [...odd, v], even ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : [ odd, [...even, v] ]&nbsp; &nbsp; , [ [], [] ]&nbsp; &nbsp; )&nbsp; &nbsp;&nbsp;console.log(result)// [ [ 1, 3 ], [ 2, 4 ] ]您可以创建一个通用函数,partition-const partition = (p, a = []) =>&nbsp; a.reduce&nbsp; &nbsp; ( ([ t, f ], v) =>&nbsp; &nbsp; &nbsp; &nbsp; p (v)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? [ [...t, v], f ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : [ t, [...f, v] ]&nbsp; &nbsp; , [ [], [] ]&nbsp; &nbsp; )const evenOdds =&nbsp; partition (v => Boolean (v & 1), [ 1, 2, 3, 4 ])const lessThan2 =&nbsp; partition (v => v < 2, [ 1, 2, 3, 4 ])&nbsp; &nbsp;&nbsp;console.log(evenOdds)// [ [ 1, 3 ], [ 2, 4 ] ]console.log(lessThan2)// [ [ 1 ], [ 2, 3, 4 ] ]

人到中年有点甜

您也可以过滤两次:&nbsp;&nbsp;const&nbsp;res&nbsp;=&nbsp;[A.filter(it&nbsp;=>&nbsp;it&nbsp;%&nbsp;2),&nbsp;A.filter(it&nbsp;=>&nbsp;!(it&nbsp;%&nbsp;2))];
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript