在javascript中比较数组

时间:2009-08-15 18:38:11

标签: javascript

我想要制作的是乐透游戏的核对清单,这对我的家人来说是一种宾果游戏。 我将首先尝试解释检查清单的作用和原因,请原谅我的技术英语,我是荷兰人,所以有些话可能是错的:)

我有一个列表,其中有几个人玩乐透/宾果游戏。所有玩家选择10个数字,每周一次有6个数字,我试着逐步解释代码必须做什么。

应该检查1到10个人的号码 每周增加2到6个数字,应该与人数进行比较 3 - 匹配时字体应为绿色 4 - 当没有匹配时字体应该保持红色

以下是我迄今为止的代码a live version is at the link

下面的代码效果很好,但问题是代码是为了比较var A和var B而设计的,这是一个瓶颈,因为它是一对一的动作。如果不添加抽奖日,我就无法添加更多人。

现在我的问题。如何在不添加B2等抽奖日期的情况下添加更多人(A1,A2,A3等)应该做些什么。

我希望这很清楚。 :)

<script type = "text/javascript">


var a1 = ["2","3","8","12","23", "37", "41", "45", "48"]
var a2 = ["2","14","3","12","24", "37", "41", "46", "48"]

var b1 = ["2","5", "11","16","23","45", "46"];
var b2 = ["1","23", "11","14","23","42", "46"];




for (var i = 0; i< a1.length; i++) 
{
    for (var j = 0; j< b1.length; j++) 
    {
        if (a1[i] == b1[j]) 
        {
            a1[i]= "g"+ a1[i];
        }
    }
}

for (var i = 0; i< a2.length; i++)
{
    for (var j = 0; j< b2.length; j++)
    {
        if (a2[i] == b2[j]) {
            a2[i]= "g"+ a2[i];
        }
    }
}

// john
document.write("<font color = '#FFFFFF'>" + "<b>" + "John &nbsp&nbsp " + "</b>");
for (var i = 0; i< a1.length; i++) 
{
    if (a1[i].substr(0,1) == "g") 
    {
        a1[i] = a1[i].substr(1,20);
        document.write("<font color = '#00FF00'>", a1[i] + " &nbsp&nbsp ");
    }
    else
    {
        document.write("<font color = '#FF0000'>", a1[i] + " &nbsp&nbsp ");
    }
}

// Michael
document.write("<br><br>");
document.write("<font color = '#FFFFFF'>" + "<b>" + "Michael &nbsp&nbsp " + "</b>");
for (var i = 0; i< a2.length; i++) 
{
    if (a2[i].substr(0,1) == "g") 
    {
        a2[i] = a2[i].substr(1,20);

        // The Draw    
        document.write("<font color = '#00FF00'>", a2[i] + " &nbsp&nbsp ");
    }
    else
    {
        document.write("<font color = '#FF0000'>", a2[i] + " &nbsp&nbsp ");
    }
}
document.write("<br><br>");
document.write("<br><br>");
document.write("<font color = '#FFFFFF'>" + "<b>" + "Draw day 1 " + "</b>");
document.write("<br>");
document.write("<font color = '#FFFFFF'>" + "<b>" + "Sat 08-08-2009 " + "</b>");
document.write("<br><br>");
for (var j = 0; j< b1.length; j++) 
{
    document.write("<font color = '#FFFFFF'>", b1[j] + " &nbsp&nbsp ");    
}
document.write("<br><br>");
document.write("<br><br>");
document.write("<font color = '#FFFFFF'>" + "<b>" + "Draw day 2 " + "</b>");
document.write("<br>");
document.write("<font color = '#FFFFFF'>" + "<b>" + "Sat 15-08-2009 " + "</b>");
document.write("<br><br>");

for (var j = 0; j< b2.length; j++) 
{
    document.write("<font color = '#FFFFFF'>", b2[j] + " &nbsp&nbsp ");
}
</script>

4 个答案:

答案 0 :(得分:4)

除了重写代码(重构)以便将数组比较为Miky D所做的函数之外,您还可以通过使用对象来保存获胜数字来提高比较效率。请注意,此代码不是最终版本;还有进一步的改进。

var guesses = [["2","3","8","12","23", "37", "41", "45", "48"],
               ["2","14","3","12","24", "37", "41", "46", "48"]];
var draws = [ {2:1, 5:1, 11:1, 16:1, 23:1, 45:1, 46:1},
                {1:1, 23:1, 11:1, 14:1, 23:1, 42:1, 46:1}];

function checkArray(guesses, draw) {
    for (var i = 0; i< guesses.length; ++i) {
        if (draw[guesses[i]]) {
            guesses[i] = 'g' + guesses[i];
        }
    }
}
checkArray(guesses[0], draws[1]);

通过将获胜数字转换为索引而不是值,您可以摆脱循环。此外,'a'和'b'不是非常具有描述性的名称。短名称只会让你感到困惑。

通过不同地标记成功和成功的猜测(目前,您将'g'添加到成功之前),您还可以简化代码以显示结果。 <font>标记已被弃用了一段时间,因此此细化使用了<span>个可以设置样式的类。

function checkArray(guesses, draw) {
    var results = {}
    for (var i = 0; i< guesses.length; ++i) {
        if (draw.picks[guesses[i]]) {
            results[guesses[i]] = 'win';
        } else {
            results[guesses[i]] = 'loss';
        }
    }
    return results;
}
...
document.write('<span class="name">John</span>');
var results = checkArray(guesses[0], draws[1]);
for (var p in results) {
    document.write('<span class="'+results[i]+'">'+p+'</span>');
}

由于document.write也已弃用,我会将其替换为现代版本document.createElementNode.appendChild。如果您认为生成的代码过于冗长,则可以使用innerHTML,但使用controversial。由于玩家名称与玩家选择密切相关,我还会按玩家名称索引玩家选择。

将以下内容放在名为“lotto.js”的文件中,与网页位于同一文件夹中。

function Result(guesses) {
    for (var i = 0; i< guesses.length; ++i) {
        this[guesses[i]] = '';
    }
}
function checkDraw(guesses, draw, results) {
    for (var i = 0; i< guesses.length; ++i) {
        if (draw.picks[guesses[i]]) {
            results[guesses[i]] = 'picked';
        }
    }
    return results;
}

function appendTo(elt, parent) {
    if (parent) {
        document.getElementById(parent).appendChild(elt);
    } else {
        document.body.appendChild(elt);
    }
}

function printResults(name, results, parent) {
    var resultElt = document.createElement('div');
    resultElt.appendChild(document.createElement('span'));
    resultElt.firstChild.appendChild(document.createTextNode(name));
    resultElt.firstChild.className='name';
    var picks = document.createElement('ol');
    picks.className='picks';
    for (var p in results) {
        picks.appendChild(document.createElement('li'));
        picks.lastChild.appendChild(document.createTextNode(p));
        picks.lastChild.className = results[p];
    }
    resultElt.appendChild(picks);
    appendTo(resultElt, parent);
}

function printResultsFor(name, draws, parent) {
    var player = players[name];
    var results = new Result(player);
    for (var i=0; i<draws.length; ++i) {
        checkDraw(player, draws[i], results);
    }
    printResults(name, results, parent);
}

function printDraw(which, draw, parent) {
    var drawElt = document.createElement('div');
    drawElt.className='draw';
    drawElt.appendChild(document.createElement('h3'));
    drawElt.lastChild.appendChild(document.createTextNode('Draw '+which));
    drawElt.lastChild.className='drawNum';
    drawElt.appendChild(document.createElement('div'));
    drawElt.lastChild.className='date';
    drawElt.lastChild.appendChild(document.createTextNode(draw.when));
    var picks = document.createElement('ol');
    picks.className='picks';
    for (var p in draw.picks) {
        picks.appendChild(document.createElement('li'));
        picks.lastChild.appendChild(document.createTextNode(p));
    }
    drawElt.appendChild(picks);
    appendTo(drawElt, parent);
}

以下是相应的HTML页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <style type="text/css">
      body {
        font-family: Verdana, Arial, Helvetica, sans-serif;
        color: white;
        background-color: #333;
      }
      .picks, .picks * {
        display: inline;
        margin: 0;
        padding: 0;
        list-style-type: none;
      }
      .picks * {
        margin: auto 0.25em;
      }
      #Results .picks * { color: red; }
      .name, .picks .name {
        color: white;
        font-weight: bold;
        margin-right: 0.5em;
      }
      #Results .picked { color: lime; }
      .drawNum, #Draws H3 {
          margin-bottom: 0;
      }
    </style>
    <script type="text/javascript" src="lotto.js"></script>
  </head>
  <body>
    <div id="Results"></div>
    <div id="Draws"></div>
    <script type="text/javascript">
    var players = {John:    [2,  3, 8, 12, 23, 37, 41, 45, 48],
                   Michael: [2, 14, 3, 12, 24, 37, 41, 46, 48]};

    var draws = [ {when: 'Sat 08-08-2009',
                   picks:{2:1, 5:1, 11:1, 16:1, 23:1, 45:1, 46:1}},
                  {when: 'Sat 15-08-2009',
                   picks:{1:1, 23:1, 11:1, 14:1, 23:1, 42:1, 46:1}}];

    for (name in players) {
      printResultsFor(name, draws, 'Results');
    }
    for (var i=0; i<draws.length; ++i) {
      printDraw(i+1, draws[i]);
    }
    </script>
  </body>
</html>

您可以优化CSS以获得所需的确切样式。代码可以进一步重构以使用OOP,这将简化创建新玩家和绘制,但它更复杂,所以我不会在这里进行。

更新:上面的代码被重写,以便每个玩家的猜测与每次抽奖进行比较。代码的live sample version已被重构,几乎无法识别使用OOP。它还使用您可能以前从未见过的功能,例如JS closureshigher order functions和CSS generated content and counters。它越来越难以理解,但更灵活,更容易使用。

答案 1 :(得分:0)

你应该使用===作为比较运算符

例如,让x = 5:

x == 8     // yield false

然而:

x == "5"   // yield **true**

===就像说“完全等于”(按值类型)

x === 5    // yield true
x === "5"  // yield false

答案 2 :(得分:0)

以下是我注意到的一些事情:

  • 您可以使用数组的数组来存储数字选择和中奖号码
  • 你真的可以创建一些功能来重复工作
  • 您从JS呈现的HTML代码未正确形成

使用函数执行重复代码

function checkArray(myValues, winningValues)
{
   for (var i = 0; i< myValues.length; i++) 
   {
      for (var j = 0; j< winningValues.length; j++) 
      {
        if (myValues[i] == winningValues[j]) 
        {
          myValues[i] = "g"+ myValues[i];
        }
      }
   }
}

function displayNumbers(playerName, myNumbers)
{
    document.write("<font color = '#FFFFFF'>" + "<b>" + playerName + " &nbsp&nbsp " + "</b></font>");
    for (var i = 0; i< myNumbers.length; i++) 
    {
       if (myNumbers[i].substr(0,1) == "g") 
       {
          myNumbers[i] = myNumbers[i].substr(1,20);
          document.write("<font color = '#00FF00'>", myNumbers[i] + "</font> &nbsp&nbsp ");
       }
       else
       {
          document.write("<font color = '#FF0000'>", myNumbers[i] + "</font> &nbsp&nbsp ");
       }
    } 
}

// then call like this
checkArray(a1, b1);

使用数组数组存储您的号码和中奖号码

var a = [["2","3","8","12","23", "37", "41", "45", "48"],
         ["2","14","3","12","24", "37", "41", "46", "48"]];

var b = [["2","5", "11","16","23","45", "46"],
         ["1","23", "11","14","23","42", "46"]];

var Players = ["John", "Michael"];

//Now you can do this:
//  for each player
for(var k = 0; k < Players.length; k++)
{
    // compare his numbers with each draw
    for(var c = 0; c < b.length; c++)
    {
       checkArray(a[k], b[c]);
       displayNumbers(Players[k], a[k]);
    }
}

添加新播放器就像

一样简单
var a = [["2","3","8","12","23", "37", "41", "45", "48"],
         ["2","14","3","12","24", "37", "41", "46", "48"]];

var b = [["2","5", "11","16","23","45", "46"],
         ["1","23", "11","14","23","42", "46"]];

var Players = ["John", "Michael"];

//Add a new player:
Players[2] = "Adam";
a[2] = ["9","3","7","12","23", "37", "40", "45", "24"];

当然,您不必同时添加人物和绘图..

答案 3 :(得分:0)

我看起来很好,谢谢!我不确定我是否做得对,但这就是我所拥有的。 但它在FireFox中不起作用。

主管部分:

<script language="javascript">

// then call like this
checkValues(a1, b1);

var a = [["2","3","8","12","23", "37", "41", "45", "48"],
     ["2","14","3","12","24", "37", "41", "46", "48"]];

var b = [["2","5", "11","16","23","45", "46"],
     ["1","23", "11","14","23","42", "46"]];

var Players = ["John", "Michael"];

//Add a new player:
Players[2] = "Adam";
a[2] = ["9","3","7","12","23", "37", "40", "45", "24"];

function checkArray(myValues, winningValues)
{
for (var i = 0; i< myValues.length; i++) 
{
  for (var j = 0; j< winningValues.length; j++) 
  {
    if (myValues[i] == winningValues[j]) 
    {
      myValues[i] = "g"+ myValues[i];
    }
  }
}
}

 function displayNumbers(playerName, myNumbers)
{
document.write("<font color = '#FFFFFF'>" + "<b>" + playerName + " &nbsp&nbsp " + "</b></font>");
for (var i = 0; i< myNumbers.length; i++) 
{
   if (myNumbers[i].substr(0,1) == "g") 
   {
      myNumbers[i] = myNumbers[i].substr(1,20);
      document.write("<font color = '#00FF00'>", myNumbers[i] + "</font> &nbsp&nbsp ");
   }
   else
   {
      document.write("<font color = '#FF0000'>", myNumbers[i] + "</font> &nbsp&nbsp ");
    }
  } 
 }

</script>

身体部分:

<body onload="checkValues(a1, b1);">