如何将列表元素组合成对
How to combine list elements into pairs
在 javascript 中是否有一个方便的函数,有或没有 underscore.js,它采用 [a, b, c, d]
形式的列表并将其转换为 [=11] 形式的列表=]?
这很容易解决 Array.prototype.map
:
var makePairs = function(arr) {
// we want to pair up every element with the next one
return arr.map(function(current, i, arr) {
// so return an array of the current element and the next
return [current, arr[i + 1]]
}).slice(0, -1)
// for every element except the last, since `arr[i + 1]` is `undefined`
}
var arr = [1, 2, 3, 4]
// you should never use `document.write`, except for in stack snippets
document.write(makePairs(arr).join("<br>"));
简而言之,没有。
但是,编写自己的函数真的很容易。这是一个比 royhowie 提出的基于地图的解决方案更快(而且我相信更容易 read/understand)的解决方案:
function pairNeighbors(arr) {
var newArray = [];
for (var i = 1; i < arr.length; i++) {
newArray.push([arr[i - 1], arr[i]]);
}
return newArray;
}
document.write(JSON.stringify(pairNeighbors([1, 2, 3, 4])));
简单的函数式编程方法是使用一些下划线辅助函数:
function consecutives(arr) {
return _.zip(_.initial(arr), _.rest(arr));
}
在 javascript 中是否有一个方便的函数,有或没有 underscore.js,它采用 [a, b, c, d]
形式的列表并将其转换为 [=11] 形式的列表=]?
这很容易解决 Array.prototype.map
:
var makePairs = function(arr) {
// we want to pair up every element with the next one
return arr.map(function(current, i, arr) {
// so return an array of the current element and the next
return [current, arr[i + 1]]
}).slice(0, -1)
// for every element except the last, since `arr[i + 1]` is `undefined`
}
var arr = [1, 2, 3, 4]
// you should never use `document.write`, except for in stack snippets
document.write(makePairs(arr).join("<br>"));
简而言之,没有。
但是,编写自己的函数真的很容易。这是一个比 royhowie 提出的基于地图的解决方案更快(而且我相信更容易 read/understand)的解决方案:
function pairNeighbors(arr) {
var newArray = [];
for (var i = 1; i < arr.length; i++) {
newArray.push([arr[i - 1], arr[i]]);
}
return newArray;
}
document.write(JSON.stringify(pairNeighbors([1, 2, 3, 4])));
简单的函数式编程方法是使用一些下划线辅助函数:
function consecutives(arr) { return _.zip(_.initial(arr), _.rest(arr)); }