如何只获取JavaScript中数组的前n%?
我们需要编写一个函数,该函数接受一个数组arr和一个介于0和100之间(包括两端)的数字n,并返回数组的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 ]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短