javascript 中是否有一个方便的函数,无论有没有 underscore.js,它都会采用 [a, b, c, d]
形式的列表,并将其转换为以下形式的列表[[a,b],[b,c],[c,d]]
?
最佳答案
使用 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>"));
关于javascript - 如何将列表元素组合成对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30607404/