好的,所以我遵循了之前的一篇关于创建一个听率监视器的文章,并对它做了一些调整,以适应我的网页设计。与设置Var数据不同,我如何一次又一次地将1到300之间的数字随机化,直到它达到200个随机数总数并绘制它们?耽误您时间,实在对不起。这是我的代码,但是我取出了大部分的Var数据,因为它有200个数字!
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#dbbd7a";
ctx.fill();
var fps = 60;
var n = 1;
var data = [
110, 149, 89, 150, 117, 150, 143, 82, 12, 92, 144, 73, 82, 200,
177, 149, 199, 116, 88, 105, 123, 12, 82, 72, 66, 15, 177, 182,
199, 116, 159, 150, 100, 10, ];
drawWave();
function drawWave() {
setTimeout(function() {
requestAnimationFrame(drawWave);
ctx.lineWidth = "1";
ctx.strokeStyle = 'green';
n += 1;
if (n >= data.length) {
n = 1;
}
ctx.beginPath();
ctx.moveTo(n - 1, data[n - 1 ]);
ctx.lineTo(n, data[n]);
ctx.stroke();
ctx.clearRect(n+1, 0, 10, canvas.height);
}, 1000 / fps);
}
</script>发布于 2015-12-04 16:20:26
有一条优雅的衬里:
var data = Array.apply(null, Array(200)).map(function(){
return Math.floor(Math.random() * 299) + 1;
});以上内容将与数组中的稀疏/假val els一起工作。
发布于 2015-12-03 19:32:41
本质是这样的:一个大小为200的数组,因为您想要200个值,并且使用一个循环随机填充值。
Math.random将生成一个介于0(包含)和1(不包括在内)之间的数字,乘以300将给出0到299.99之间的任何数字。Math.floor()删除小数位(范围变为0和299);因此,我们在末尾添加1,以获得所需的1至300范围。
希望这能有所帮助
var data = [];
for(var i = 0; i < 200; ++i) {
data[i] = Math.floor(Math.random() * 300) + 1;
}发布于 2015-12-03 19:46:34
这样做的一个简单方法是:
// creating a new Array with a length of 20 (obviously
// adjust the '20' to '200' for your own use-case):
var arr = new Array(20);
// using Array.prototype.fill() to assign a value (an
// empty String) to each array element, in order that
// Array.prototype.forEach() can iterate over each array
// element:
arr.fill('').forEach(function(needle, i, haystack){
// the arguments are automagically available to the
// the anonymous function;
// needle: the current array-element of the Array,
// i: the index of the current array-element,
// haystack: the Array itself.
// here we set the array value using bracket notation:
haystack[i] = Math.floor(Math.random() * (300 - 1) + 1);
});
// outputting the array to the console:
console.log( arr );
var arr = new Array(20);
arr.fill('').forEach(function(needle, i, haystack) {
haystack[i] = Math.floor(Math.random() * (300 - 1) + 1);
});
// Setting the array as the text of the <body> element,
// given the lack of a Snippet console:
document.body.textContent = arr.join(', ') + '.';
JS Fiddle演示。
发布的解决方案中在一定范围内生成随机数的部分:
Math.floor(Math.random() * (300 - 1) + 1)实际上是从网站其他地方借用的(https://stackoverflow.com/a/1527820/82548,由奥努特·G·斯坦编写),并在这个答案中解释。
但是,简单地说,它生成0到1之间的随机数;乘以299 (300-1),使得整数部分变成0到299之间的数字;然后添加1以确保整数现在在1和300之间。
然后,我们应用Math.float()将该随机数与该数的整数部分相加。上面我联系到的答案更完整地解释了这一点。
参考文献:
https://stackoverflow.com/questions/34074505
复制相似问题