等效于Ruby中的Ruby的each_cons [英] Equivalent of Ruby's each_cons in JavaScript
本文介绍了等效于Ruby中的Ruby的each_cons的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人问了这个问题,要求提供多种语言,而不是javascript.
Ruby具有方法 Enumerable#each_cons
看起来像这样:
puts(0..5).each_cons(2).to_a#[[0,1],[1,2],[2,3],[3,4],[4,5]]放(0..5).each_cons(3).to_a#[[1、2、3],[2、3、4],[3、4、5]]
我如何在javascript中为 Array
使用类似的方法?
解决方案
以下是可以实现此功能的函数(ES6 +):
//功能方法const eachCons =(array,num)=>{return Array.from({length:array.length-num + 1},(_,i)=>array.slice(i,i + num))}//原型替代方法Array.prototype.eachCons = function(num){return Array.from({length:this.length-num + 1},(_,i)=>this.slice(i,i + num))}const array = [0,1,2,3,4,5]const log = data =>console.log(JSON.stringify(data))日志(eachCons(array,2))日志(eachCons(array,3))日志(array.eachCons(2))log(array.eachCons(3))
您必须猜测所得数组的长度( n = length-num + 1
),然后才能利用JavaScript的Enumerable#each_cons
which look like that:
puts (0..5).each_cons(2).to_a
# [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
puts (0..5).each_cons(3).to_a
# [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
How could I have a similar method in javascript for Array
?
解决方案
Here is a function that will do it (ES6+):
// functional approach
const eachCons = (array, num) => {
return Array.from({ length: array.length - num + 1 },
(_, i) => array.slice(i, i + num))
}
// prototype overriding approach
Array.prototype.eachCons = function(num) {
return Array.from({ length: this.length - num + 1 },
(_, i) => this.slice(i, i + num))
}
const array = [0,1,2,3,4,5]
const log = data => console.log(JSON.stringify(data))
log(eachCons(array, 2))
log(eachCons(array, 3))
log(array.eachCons(2))
log(array.eachCons(3))
You have to guess the length of the resulting array (n = length - num + 1
), and then you can take advantage of JavaScript's array.slice
To get the chunks you need, iterating n
times.
这篇关于等效于Ruby中的Ruby的each_cons的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文