生成随机数时向数组添加值

时间:2013-06-20 20:31:55

标签: javascript

我希望得到一个随机数生成器添加到空数组的一些帮助。

你能告诉我如何在javascript中做到这一点。我已经输出了随机数 - 随机数字数组 - 然后随机选择数组并输出数字。每次按下随机按钮时,如何创建另一个存储值的数组?

    // Suites

var suites= new Array();
suites[0] = "Hearts";
suites[1] = "Spades";
suites[2] = "Diamonds";
suites[3] = "Clubs";

    // Values

var values = new Array();
values[0] = "Ace";
values[1] = "King";
values[2] = "Queen";
values[3] = "Jack";
values[4] = "2";
values[5] = "3";
values[6] = "4";
values[7] = "5";
values[8] = "6";
values[9] = "7";
values[10] = "8";
values[11] = "9";
values[12] = "10";    

function myFunction()
{
    var x=document.getElementById("demo")
    var y=document.getElementById("demo2")
    x.innerHTML= values[Math.floor((Math.random())*12)]
    y.innerHTML= suites[Math.floor((Math.random())*4)]
}

http://jsfiddle.net/Eddybaby/RmtkF/

2 个答案:

答案 0 :(得分:0)

使用push更新阵列:

var storeArray = [];

function onButtonPress(newValue){
    //do other stuff here?
    storeArray.push(newValue);
}

答案 1 :(得分:0)

我建议使用更干净的OOP解决方案。 使用card对象构造函数来存储每张卡,这样您就可以轻松传递它并使用push将其存储在数组中。

http://jsfiddle.net/WLuu4/

var dealistory = new Array(); //array that will hold all cards generated

//card constructor
function card(value, suite){ 
    return ({
        'value': value,
        'suite': suite
    });
}

//random card generator
function randomCard(){

    var suites = ["Hearts","Spades","Diamonds","Clubs"];
    var values = ["Ace","King","Queen","Jack","2","3","4","5","6","7","8","9","10"];

    var s = values[Math.floor((Math.random()) * 12)];
    var v = suites[Math.floor((Math.random()) * 4)];

    return card(s, v);
}

//deal button action
deal.onclick = function(){

    var newCard = randomCard();

    document.getElementById("demo").innerHTML = newCard.value;
    document.getElementById("demo2").innerHTML = newCard.suite;

    dealHistory.push(newCard); //add card to history array
    console.log(dealHistory);
}

dealHistory数组示例:
enter image description here


编辑:

我添加了一个函数printCard来为每张卡生成html,并添加一个函数printHist来遍历调用printCard的历史数组,以显示屏幕上的每个项目。

http://jsfiddle.net/WLuu4/1/

enter image description here

//generate html for a card
function printCard(card){

    var cardHTML = '';
    cardHTML+='<div class="card">';
    cardHTML+='<div class="suite">'+card.suite+'</div>'
    cardHTML+='<div class="value">'+card.value+'</div>'
    cardHTML+='</div>';

    return cardHTML;
}

//generate html for each card in an array
function printHist(array){
    var html="";
    for(var i=0; i<array.length; i++){
        html += printCard(array[i]);
    }
    return html;
}