你知道如何循环吗?

时间:2016-12-19 08:32:29

标签: javascript

示例我们有这个js数组(某些类似lat,lng):

items = [
[aa,aa],
[bb,bb],
[cc,cc]
]

我期望的结果应该是这样的:

A = [
[aa,aa],
[bb,bb]
]
B = [
[bb,bb],
[cc,cc]
]

2 个答案:

答案 0 :(得分:2)

您正在尝试迭代两个连续的元素(数组),您可以使用ruby_cons

  

注意:这是一个迭代连续元素的Ruby解决方案。

items.each_cons(2) do |arr|
  p arr
end

答案 1 :(得分:1)

在javascript中,你可以试试......,

> items
[ [ 42.32, 47.32 ], [ 49.434, 41.343 ], [ 43.34, 43.45 ] ]
> container = []
[]
> for(var i = 0; i<items.length-1; i++) {
... container.push(items.slice(i, i+2));
... }
2
> container[0]
[ [ 42.32, 47.32 ], [ 49.434, 41.343 ] ]
> container[1]
[ [ 49.434, 41.343 ], [ 43.34, 43.45 ] ]

更广泛的解决方案,灵感来自ruby的each_cons(n)可枚举方法。

>     each_cons = function(enm, cons_size) {
...       var results = [];
...       /* 
...        *  checking numericality like typeof cons_size == 'number'  
...        *  might be useful. but i'am skipping it.
...        */
...       cons_size = (cons_size < 1 ? 1 : cons_size ); 
...       // setting default to 2 might be more reasonable
...       for (var i=0; i<=enm.length - cons_size; i++) {
.....         results.push(enm.slice(i, i+cons_size));
.....       }
...       return results;
...     }
[Function: each_cons]
> x = [1,2,3,4,5,6,7,8,9,0];
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ]
> each_cons(x, 0)
[ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 0 ] ]
> each_cons(x, 1)
[ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 0 ] ]
> each_cons(x, 2)
[ [ 1, 2 ],
  [ 2, 3 ],
  [ 3, 4 ],
  [ 4, 5 ],
  [ 5, 6 ],
  [ 6, 7 ],
  [ 7, 8 ],
  [ 8, 9 ],
  [ 9, 0 ] ]
> each_cons(x, 3)
[ [ 1, 2, 3 ],
  [ 2, 3, 4 ],
  [ 3, 4, 5 ],
  [ 4, 5, 6 ],
  [ 5, 6, 7 ],
  [ 6, 7, 8 ],
  [ 7, 8, 9 ],
  [ 8, 9, 0 ] ]
>
> x= "hippopotomonstrosesquipedaliophobia"; //https://en.wiktionary.org/wiki/hippopotomonstrosesquipedaliophobia
'hippopotomonstrosesquipedaliophobia'
> each_cons(x, 3)
[ 'hip',
  'ipp',
  'ppo',
  'pop',
  'opo',
  'pot',
  'oto',
  'tom',
  'omo',
  'mon',
  'ons',
  'nst',
  'str',
  'tro',
  'ros',
  'ose',
  'ses',
  'esq',
  'squ',
  'qui',
  'uip',
  'ipe',
  'ped',
  'eda',
  'dal',
  'ali',
  'lio',
  'iop',
  'oph',
  'pho',
  'hob',
  'obi',
  'bia' ]
> 

> x = [[1,2], ['a', 'b'], [2,3,4, {a: 5}]]
[ [ 1, 2 ], [ 'a', 'b' ], [ 2, 3, 4, { a: 5 } ] ]
> each_cons(x, 2)
[ [ [ 1, 2 ], [ 'a', 'b' ] ],
  [ [ 'a', 'b' ], [ 2, 3, 4, [Object] ] ] ]