JavaScript从单一值的数组返回值配对的新数组 [英] javaScript to return a new array of paired values from an array of single values

查看:109
本文介绍了JavaScript从单一值的数组返回值配对的新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  阵列分割成块


我试图值的数组转换成配对值的新数组。

例如我需要转换:

  VAR ARR = [1,2,3,4,5];

  ARR = [[1,2],[3,4],[5,6],[7,8];

我试着使用jQuery的.MAP()方法,像这样,但这并没有为我工作:

  ARR = $ .MAP(ARR,功能(N,I){
返回[N +','+ N [I + 1]];
});


解决方案
关于使用

如果你坚持的地图,你可以做这样的:

  ARR = $ .MAP(ARR,功能(N,I){
    如果(I%2 === 0)返回[N,ARR [I + 1]]];
});

Possible Duplicate:
Split array into chunks

I am trying to convert an array of values into a new array of paired values.

For example i need to convert:

var arr = [1,2,3,4,5,6,7,8];

into:

arr = [[1,2], [3,4], [5,6], [7,8]];

I tried using jQuery's .map() method like so but this did not work for me:

arr= $.map(arr, function(n, i){
return [n + ',' + n[ i + 1 ]];
});

解决方案

If you insist on using map, you could do it like this:

arr= $.map(arr, function(n, i){
    if (i%2 === 0) return [[n, arr[ i + 1 ]]];
});

这篇关于JavaScript从单一值的数组返回值配对的新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆