简体   繁体   English

将数组大小调整为指定长度并均匀分配索引值

[英]Resize array to specified length and evenly distribute value of indexes

I am very bad at math, so forgive me if this is super obvious, I did do research and couldn't find anything matching what I need. 我很擅长数学,所以请原谅我,如果这是非常明显的,我确实做了研究,找不到符合我需要的东西。

I'm trying to make my audio analyser responsive in width. 我正在努力让我的音频分析仪在宽度上做出响应。 This has proven to be very difficult, as the frequency array has a fixed size. 事实证明这非常困难,因为频率阵列具有固定的尺寸。

By calculating the width of each bar, and against the width of the canvas, I can easily find out how many bars could fit inside it. 通过计算每个条的宽度,并相对于画布的宽度,我可以很容易地找出它内部可以容纳多少条。

So let's say the canvas is 20 pixels wide, and each bar is 4 pixels wide (including space between). 因此,假设画布宽度为20像素,每个条形宽度为4像素(包括间距)。 That would mean 5 bars could fit inside the canvas. 这意味着5个条可以放在画布内。 So using this information, we could create a function that resizes the frequency array length to 5, and evenly distributes frequencies into those 5 indexes. 因此,使用此信息,我们可以创建一个将频率数组长度调整为5的函数,并将频率均匀分配到这5个索引中。

This way no frequency range is left out, and the analyser can be resized to any width, and still fill the space. 这样就不会遗漏任何频率范围,并且分析仪可以调整到任何宽度,并且仍然可以填充空间。

function resize(array, integer) {
    ...
    return result;
}

array = [1, 2, 3, 4, 5... 100] // Array that goes from 1 to 100 (100 indexes)

resize(array, 10) // [1, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Here's the original array displayed on the canvas (the dotted bars are the ones that are outside of the canvas) 这是画布上显示的原始数组(虚线条是画布外部的数组)

在此输入图像描述

Now I want to resize the array so that the bars fit in the canvas like this (20 bars in this example) 现在我想调整数组的大小,使条形像这样适合画布(本例中为20条)

在此输入图像描述

I really hope I explained myself well here, this was very difficult to explain 我真的希望我在这里解释得很好,这很难解释

This solution works. 此解决方案有效。 Now. 现在。 With returning the nth value factor of the original array. 返回原始数组的第n个值factor

 function arrayResize(array, integer) { var factor = array.length / integer; return Array.apply(null, { length: integer }).map(function (_, i) { return array[Math.floor(i * factor)]; }); } var array = Array.apply(null, { length: 100 }).map(function (_, i) { return Math.floor(i / 10); }); document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>'); document.write('<pre>' + JSON.stringify(arrayResize(array, 5), 0, 4) + '</pre>'); document.write('<pre>' + JSON.stringify(arrayResize(array, 10), 0, 4) + '</pre>'); document.write('<pre>' + JSON.stringify(arrayResize(array, 20), 0, 4) + '</pre>'); 

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

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