简体   繁体   English

如何只获取数组的前 n%?

[英]How to get only the first n% of an array?

I have a sorted array like this:我有一个这样的排序数组:

array [0, 0, 0, 1, 3, 5, 5, 6, 6, 6, 6, 8, 8, 8, 9, 9];数组 [0, 0, 0, 1, 3, 5, 5, 6, 6, 6, 6, 8, 8, 8, 9, 9];

I want to view only the first n% of the array.我只想查看数组的前 n%。 I need the principle or advice on what to use (loop, slice, ...) to achieve this.我需要关于使用什么(循环,切片,...)来实现这一点的原则或建议。

You could take the length of the array and the percent value and slice the array.您可以获取数组的长度和百分比值并对数组进行切片。

 function getPercent(array, percent) { return array.slice(0, Math.ceil(array.length * percent / 100)); } var array = [0, 0, 0, 1, 3, 5, 5, 6, 6, 6, 6, 8, 8, 8, 9, 9]; console.log(...getPercent(array, 10)); console.log(...getPercent(array, 20)); console.log(...getPercent(array, 30));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM