2006-06-20
TAG:JavaScript

今天在开发当中要用javascript实现一个功能,从数据库随机抽取一道题 四个选项,在客户端要求把四个选项也随机打乱。我的思路是如此。

1、首先把四个选项装入一个数组

2、使用Math.floor(Math.random() * 数字)随机抽取出来一个数字作为数组的一个下标

4、把此下标对应的内容填充到一个string里 然后remove掉数组中的该元素

然后再执行第2步骤直到数组中只有一个元素

需要说明的是Math.floor(Math.random() * 数字)下标是从零开始的 比如Math.floor(Math.random() * 4) 随机将从0-3随机选出 永远都不会出现4这个数字。

代码如下 [另外 因为javascript中的数组对象没有remove函数 所以我另外提供两个自定义的remove函数]

Array.prototype.remove=function(dx)
{
    if(isNaN(dx)||dx>this.length){return false;}
    for(var i=0,n=0;i    {
        if(this[i]!=this[dx])
        {
            this[n++]=this[i]
        }
    }
    this.length-=1
}

function a()
{
Option1="1";
Option2="2";
Option3="3";
Option4="4";
arraystring = new Array(4);
var Options="";
arraystring[0] ="+Option1+"
\n";
arraystring[1] ="+Option2+"
\n";
arraystring[2] ="+Option3+"
\n";
arraystring[3] ="+Option4+"
\n";
var index=0;
index = parseInt(Math.floor(Math.random() * 4));
alert(index);
Options+=arraystring[index].toString();
arraystring.remove(index);
index =parseInt(Math.floor(Math.random() * 3));
alert(index);
Options+=arraystring[index].toString();
arraystring.remove(index);
index = parseInt(Math.floor(Math.random() * 2));
alert(index);
Options+=arraystring[index].toString();
arraystring.remove(index);
Options+=arraystring[0].toString();

alert(Options);

JavaScript通过设置数组的length属性来截断数组是惟一一种缩短数组长度的方法.如果使delete运算符来删除数组中元素,虽然那个元素变成未定义的,但是数组的length属性并不改变.两种删除元素,数组长度也改变的方法.

/*
 *  方法:Array.remove(dx)
 *  功能:删除数组元素.
 *  参数:dx删除元素的下标.
 *  返回:在原数组上修改数组
 */

//经常用的是通过遍历,重构数组.
Array.prototype.remove=function(dx)
{
    if(isNaN(dx)||dx>this.length){return false;}
    for(var i=0,n=0;i    {
        if(this[i]!=this[dx])
        {
            this[n++]=this[i]
        }
    }
    this.length-=1
}
a = [''''1'''',''''2'''',''''3'''',''''4'''',''''5''''];
alert("elements: "+a+"\nLength: "+a.length);
a.remove(0); //删除下标为0的元素
alert("elements: "+a+"\nLength: "+a.length);

/*
 *  方法:Array.baoremove(dx)
 *  功能:删除数组元素.
 *  参数:dx删除元素的下标.
 *  返回:在原数组上修改数组.
 */

//我们也可以用splice来实现.

Array.prototype.baoremove = function(dx)
{
    if(isNaN(dx)||dx>this.length){return false;}
    this.splice(dx,1);
}
b = [''''1'''',''''2'''',''''3'''',''''4'''',''''5''''];
alert("elements: "+b+"\nLength: "+b.length);
b.baoremove(1); //删除下标为1的元素
alert("elements: "+b+"\nLength: "+b.length);






坯子 @ 11:52:20 | 引用 0 | 编辑



评论
 
java综合网 (http://www.javazh.cn) @ 2007-12-30 22:46:48
http://www.javazh.cn
不错,不错



发表评论
 姓名: 
 E-mail: 
 地址: