I want a very simple feature, I hope use short and beautiful code to do below
input:
[1,2,3,4,5,6,7,8,9,10]
output:
[[1,2],[3,4],[5,6],[7,8],[9,10]]
how to do this in javascript
I want a very simple feature, I hope use short and beautiful code to do below
input:
[1,2,3,4,5,6,7,8,9,10]
output:
[[1,2],[3,4],[5,6],[7,8],[9,10]]
how to do this in javascript
配列を変更する別のフレーバーを次に示します(偶数の配列エントリを想定しています)。
var orig = [1,2,3,4,5,6,7,8,9,10];
for (var i = 0; i < orig.length; i+=2) {
orig[i/2] = [orig[i], orig[i+1]];
}
orig.length /= 2;
function splitPairs(arr) {
var newArr = new Array(Math.round(arr.length / 2));
for (var i=0, l=arr.length; i<l; i+=2) {
newArr[i>>1] = [arr[i], arr[i+1]];
}
return newArr;
}
2行:
function cut(ar)
{
for(var i=0,l=ar.length,tmpar=[];i<l;i+=2)tmpar[tmpar.length]=[ar[i],ar[i+1]];
return tmpar;
}
また、配列内の要素の数が奇数の場合も機能します:http: //jsfiddle.net/7yd26/4/