Quantcast
Channel: CodeBit.cn » shuffle
Viewing all articles
Browse latest Browse all 3

为 Javascript 数组添加 shuffle 方法

$
0
0

PHP 里面有个非常方便的打乱数组的函数 shuffle() ,这个功能在许多情况下都会用到,但 javascript 的数组却没有这个方法,没有不要紧,可以扩展一个,自己动手,丰衣足食嘛。

为 Javascript 数组添加 shuffle 方法 – 示例

 
<script type="text/javascript">
//<![CDATA[
// 说明:为 Javascript 数组添加 shuffle 方法
// 整理:http://www.CodeBit.cn

var shuffle = function(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

document.write("A = ", a.join(","), "<br />shuffle(A) = ", shuffle(a));

//]]>
</script>

通过 prototype 给数组添加一个方法:

 
<script type="text/javascript">
//<![CDATA[

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

if (!Array.prototype.shuffle) { 
	Array.prototype.shuffle = function() {
		for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
		return this;
	};
}

document.write("A = ", a.join(","), "<br />A.shuffle() = ", a.shuffle());

//]]>
</script>

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles



Latest Images