如何在 JavaScript 中仅获得数组前 n% 的数据?
我们需要编写一个函数,该函数接受一个数组 arr 和一个数字 n(介于 0 和 100(含)之间),并返回数组的 n% 部分。例如,如果第二个参数为 0,我们应该预料一个空数组,如果是 100 则为完整数组,如果是 50 则为一半,等等。
如果未提供第二个参数,则其默认值应为 50。因此,代码如下所示:
实例
const numbers = [3,6,8,6,8,4,26,8,7,4,23,65,87,98,54,32,57,87];
const byPercent = (arr, n = 50) => {
const { length } = arr;
const requiredLength = Math.floor((length * n) / 100);
return arr.slice(0, requiredLength);
};
console.log(byPercent(numbers));
console.log(byPercent(numbers, 84));
console.log(byPercent(numbers, 34));输出
控制台中的输出将为:
[ 3, 6, 8, 6, 8, 4, 26, 8, 7 ] [ 3, 6, 8, 6, 8, 4, 26, 8, 7, 4, 23, 65, 87, 98, 54 ] [ 3, 6, 8, 6, 8, 4 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP