如何使用JavaScript随机向数组添加值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用JavaScript随机向数组添加值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2145字,纯文字阅读大概需要4分钟。
内容图文
![如何使用JavaScript随机向数组添加值](/upload/InfoBanner/zyjiaocheng/779/bdb4980dc5e4406aab9473190fca7ee2.jpg)
我是JavaScript的新手,我正在完成一项任务,我必须在12次加载之间随机分散输入值.另一方面是阵列的每个元素与下一个元素的不同之处不止一个.
所以例如,如果我有30的数量,我需要在12只骆驼之间分配这个数额.我到目前为止编写了下面的代码,但我正在使用TextPad,我不知道如何在同一行打印出结果.
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0]
var div = amount/12;
var mod = amount%12;
var x = mod / 12;
for(i=0;i<camels.length;i++){
WScript.echo(camels[i] + "|" + Math.floor(div) + "|" + mod + "|" + x)
}
如果您需要更多信息请评论,谢谢
解决方法:
这是我的看法.请注意,对于声明数组值与下一个数组不能超过一个的要求,我认为数组是循环的,即最后一个值之后的值是第一个值.
var amount = 30;
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
while (amount > 0) {
var index = Math.floor(Math.random() * camels.length);
var previous = (camels.length + index - 1) % camels.length;
var next = (index + 1) % camels.length;
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
camels[index]++;
amount--;
}
}
更新
根据OP的要求,这是一个带注释的版本:
// the amount that needs to be distributed among the camels
var amount = 30;
// the actual values for all 12 camels, initially all zero
var camels = [0,0,0,0,0,0,0,0,0,0,0,0];
// as long as we have something to distribute
while (amount > 0) {
// get a random current index in the array, i.e. a value between 0 and 11
var index = Math.floor(Math.random() * camels.length);
// calculate the index previous to the current index;
// in case the current index is 0, the previous index will be 11
var previous = (camels.length + index - 1) % camels.length;
// calculate the index next to the current index;
// in case the current index is 11, the next index will be 0
var next = (index + 1) % camels.length;
// if adding 1 to the camel at the current index makes it so that
// the difference with the camel at the previous index is 1 or lower
// the difference with the camel at the next index is 1 or lower
if (Math.abs(camels[index] + 1 - camels[previous]) <= 1
&& Math.abs(camels[index] + 1 - camels[next]) <= 1) {
// go ahead and add 1 to that camel
camels[index]++;
// and decrement the amount accordingly
amount--;
}
}
内容总结
以上是互联网集市为您收集整理的如何使用JavaScript随机向数组添加值全部内容,希望文章能够帮你解决如何使用JavaScript随机向数组添加值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。