js将一位数组分割成每三个一组

2021-04-27  本文已影响0人  keknei
var data = [
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
  {name:'Liming',age:'25'},
]
var result = [];
for(var i=0;i<data.length;i+=3){
    result.push(data.slice(i,i+3));
}

巧妙的运用了slice方法不会改变原数组,并且返回一个新的数组,而且当slice(start,end)第二个end参数值大于数组length的时候,会按照数组length算,取的数组结束的所有元素

上一篇下一篇

猜你喜欢

热点阅读