本文介绍了Javascript:取数组的每个第 n 个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个数据数量未知的数组.但我只有预定义的数据量要显示/存储.如何在 JavaScript 中获取初始数组的每个第 n 个元素并减少它?

例如:我得到一个大小为 10000 的数组,但只能显示 n=2k 个元素.

我是这样试的:delta= Math.round(10*n/size)/10 = 0.2 -> 取初始数组的每 5 个元素.

for (i = 0; i 

对于 0.2,它始终为 0,但对于其他一些增量 (0.3),它可以正常工作.delta=0.4 也一样,我工作,但每隔一个 Element 就会被占用.我该怎么做才能让它发挥作用?

解决方案

也许有一个解决方案:

避免使用过滤器,因为您不想循环超过 10 000 个元素!只需使用 for 循环直接访问它们!

var log = function(val){document.body.innerHTML+='<div></pre>'+val+'</pre></div>'}var oldArr = [0,1,2,3,4,5,6,7,8,9,10]var arr = [];无功maxVal = 5;var delta = Math.floor( oldArr.length/maxVal );//避免过滤,因为你不想要//循环超过 10000 个元素!//只需使用 for 循环直接访问它们!//|//Vfor (i = 0; i < oldArr.length; i=i+delta) {arr.push(oldArr[i]);}log('delta :' + delta + 'length = ' + oldArr.length);日志(arr);

I get an Array with an unknown Number of data.But I only have an predefined amount of data to be shown/store.How can I take every nth Element of the initial Array and reduce it in JavaScript?

Eg.: I get an Array with size=10000, but are only able to show n=2k Elements.

I tried it like that:delta= Math.round(10*n/size)/10 = 0.2 -> take every 5th Element of the initial Array.

for (i = 0; i < oldArr.length; i++) {
  arr[i] = oldArr[i].filter(function (value, index, ar) {
    if (index % delta != 0) return false;
    return true;
  });
}

With 0.2 it´s always 0, but with some other deltas (0.3) it is working. Same for delta=0.4, i works, but every second Element is taken with that. What can I do to get this to work?

解决方案

Maybe one solution :

avoid filter because you don't want to loop over 10 000 elements !just access them directly with a for loop !


var log = function(val){document.body.innerHTML+='<div></pre>'+val+'</pre></div>'}

var oldArr = [0,1,2,3,4,5,6,7,8,9,10]
var arr = [];

var maxVal = 5;

var delta = Math.floor( oldArr.length / maxVal );

// avoid filter because you don't want
// to loop over 10000 elements !
// just access them directly with a for loop !
//                                 |
//                                 V
for (i = 0; i < oldArr.length; i=i+delta) {
  arr.push(oldArr[i]);
}


log('delta : ' + delta + ' length = ' + oldArr.length) ;
log(arr);

这篇关于Javascript:取数组的每个第 n 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:08