
开篇寄语
伯衡君在开发游戏的过程中,时常会遇到这样一个问题,就是要在指定数组Array中随机排列这组数据,并且要从中随机取值,那么问题来了,该如何处理这种问题呢,伯衡君就以Javascript这门编程语言为例,介绍如何处理这样的问题好了,于是就有了这篇文章。
其他编程语言处理
内容详情
给定一个数组,比如:
var arr = [1,2,3,4,5,6,7,8,9]
如何处理?肯定是需要遍历这个数组,之后将里面的各个数值的index位置改变,势必会用到Math.random(),之后按照这样的思想,可以这样解决:
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
然后输出结果就会变成这样:
shuffle(arr); //输出结果为:[9, 0, 8, 3, 2, 7, 1, 4, 5, 6]
你甚至还可以将它构建为处理数组的一种方法,就像arr.map,arr.filter等,方法如下:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
});
//或者用这种方式构建
Array.prototype.shuffle = function(arr){
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
之后,就可以在实际应用中这样使用:
arr.shuffle() //输出结果为:[4, 9, 6, 8, 0, 2, 7, 5, 3, 1]
接下来是从数组取随机数,这就比较简单了,代码如下:
arr[Math.floor(Math.random()*arr.length)];
总结
总之,处理问题的时候,就要将之分解为一步步可以执行的操作,将困难问题简单化,这些问题就能迎刃而解了。
- 我的微信
- 微信扫一扫加好友
-
- 我的微信公众号
- 扫描关注公众号
-





