使用 .map 或 underscore.js 在 javascript 中重构 while 循环
Refactoring a while loop in javascript using .map or underscore.js
好的,所以我的代码中有这个非常糟糕的 while 循环。我正在尝试重构它以在 js 中使用 Underscore.js 或 .map 函数,但我一直卡住了。这是我的工作代码:
createGroupedChannels = (array) ->
groups = []
i = 0
column = 0
while i < array.length
if groups.length <= 2
groups.push [array[i]]
i += 1
else
groups[column].push array[i]
column += 1
i += 1
if column is 3
column = 0
groups.reverse()
重点是将数组拆分为3组,并保持初始的相对顺序。我尝试了几种尝试使用下划线的配置,但都无济于事。我是 JS 的新手,非常感谢任何帮助。
我目前拥有的 .map 根本不起作用,但我正在根据要求添加它:
createGroupedChannels = (array) ->
_.map array, () ->
i = 0
column = 0
groups = []
if groups.length <= 2
groups.push [array[i]]
else
groups[column].push array[i]
i += 1
column += 1
column = 0 if column is 3
groups.reverse()
没有 Array.prototype.map
,但有 Array.prototype.reduce
:
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
groups = data.reduce(function (r, a, i) {
r[i % 3].push(a);
return r;
}, [[],[],[]]);
document.write('<pre>' + JSON.stringify(groups, 0, 4) + '</pre>');
好的,所以我的代码中有这个非常糟糕的 while 循环。我正在尝试重构它以在 js 中使用 Underscore.js 或 .map 函数,但我一直卡住了。这是我的工作代码:
createGroupedChannels = (array) ->
groups = []
i = 0
column = 0
while i < array.length
if groups.length <= 2
groups.push [array[i]]
i += 1
else
groups[column].push array[i]
column += 1
i += 1
if column is 3
column = 0
groups.reverse()
重点是将数组拆分为3组,并保持初始的相对顺序。我尝试了几种尝试使用下划线的配置,但都无济于事。我是 JS 的新手,非常感谢任何帮助。
我目前拥有的 .map 根本不起作用,但我正在根据要求添加它:
createGroupedChannels = (array) ->
_.map array, () ->
i = 0
column = 0
groups = []
if groups.length <= 2
groups.push [array[i]]
else
groups[column].push array[i]
i += 1
column += 1
column = 0 if column is 3
groups.reverse()
没有 Array.prototype.map
,但有 Array.prototype.reduce
:
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
groups = data.reduce(function (r, a, i) {
r[i % 3].push(a);
return r;
}, [[],[],[]]);
document.write('<pre>' + JSON.stringify(groups, 0, 4) + '</pre>');