简体   繁体   English

如何在 javascript 中创建一个可变条件作为参数?

[英]How can I create a variable condition as a parameter in javascript?

I want to test how many red/black/even/odd comes up in a row in the game of roulette.我想测试轮盘游戏中连续出现多少红色/黑色/偶数/奇数。

The following function will loop through a list of spins n and give how many times in a row red won and lost.以下 function 将遍历旋转列表 n 并给出红色连续赢和输的次数。 The same function can be used for all the other types of even wins however the check is different相同的 function 可用于所有其他类型的偶赢,但支票不同

color[n[i]] == "red"

I want to pass a different check into this function to test for evens我想通过不同的支票进入这个 function 来测试偶数

n[i]%2 == 0

Can this be done?这可以做到吗?

function test(n)
{
    var wins = parseInt(0);
    var losses = parseInt(0);

    for(var i=0;i<n.length;i++)
    {
        if(color[n[i]] == "red")
        {
            wins += 1 
            losses = 0
        }
        else
        {
            wins = 0
            losses += 1
        }

    }
.
.
.

PART 2第2部分

This is the full code.这是完整的代码。 If you click the 'Enter Spins' button and the 'Toggle Number Pad' button, then add the number 8 twice, then 3 alerts will display.如果您单击“输入旋转”按钮和“切换数字键盘”按钮,然后两次添加数字 8,则会显示 3 个警报。

I can not seem to get the the 3 messages to show up on separate lines.我似乎无法让 3 条消息显示在不同的行上。 I tried some examples, but it always adds the line return before the last message.我尝试了一些示例,但它总是在最后一条消息之前添加行返回。 Do you know how to get the multiple messages on separate lines?你知道如何在不同的行上获取多条消息吗?

<html>
<head>
<style>
.bntcal {
    padding: 10px 10px 10px 10px;
    margin: 10px;
}
.bntcaladd {
    padding: 10px 10px 10px 10px;
    margin: 10px;
}

.bntshow{
    padding: 5px 5px 5px 5px;
    margin: 5px;
    width: 10%;
}
.spanhide {
    display: none;
}
.bell {
    float:left;
    display: none;
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var wheel0 = [37,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26];
var wheel00 = [37,28,9,26,30,11,7,20,32,17,5,22,34,15,3,24,36,13,1,38,27,10,25,29,12,8,19,31,18,6,21,33,16,4,23,35,14,2];
var wheel = wheel00;
var wColor = "";
var numbers = [];
var color = [];



$(document).ready(function(){

    // --- Menu Buttons
    $("#enterSpins").click(function(){
        $("#divSpins").show();
        $("#divAlerts").hide();
        $("#divHowTo").hide();
    });

    $("#setAlert").click(function(){
        $("#divAlerts").show();
        $("#divSpins").hide();
        $("#divHowTo").hide();
    });

    $("#howTo").click(function(){
        $("#divHowTo").show();
        $("#divSpins").hide();
        $("#divAlerts").hide();

    });

    // ---- Sub Buttons
    $("#enterPad").click(function(){
        $("#showSpinsPad").toggle();
        $("#clearBox").toggle();
        $("#clearBox1").toggle();
        if(!$("#showSpinsPad").is(":hidden"))
        {
            $("#spins").prop("disabled", true)
        }
        else
        {
            $("#spins").prop("disabled", false)
        }

    }); 

    $(".bntcal").click(function(){
        $("#currentSpin").text($("#currentSpin").text()+$(this).val())
        if ($("#currentSpin").text().length > 2)
        {
            $("#currentSpin").text($(this).val())
        }    
    });


    $("#clear").click(function(){
        $("#currentSpin").text("")
    });

    $("#add").click(function(){

        getWheel()
        currentSpin = $("#currentSpin").text()
        if(currentSpin.length > 0)
        {
            if ($("#spins").val().length > 0)
            {
                $("#spins").val($("#spins").val() + ", ");
            }
            if(parseInt(currentSpin)<37)
            {
                $("#spins").val($("#spins").val() + currentSpin);
            }
            if(parseInt(currentSpin) == 37)
            {
                $("#spins").val($("#spins").val() + "0");
            }
            if(parseInt(currentSpin) == 38)
            {
                $("#spins").val($("#spins").val() + "00");
            }
            if(parseInt(currentSpin)>38)
            {
                $("#spins").val($("#spins").val() + "0");
            }

            $("#currentSpin").text("") 
        }

        var n = GetUserNumbers();
        run(n)
    });

    $("#undo").click(function(){
        var n = GetUserNumbers();

        if (n.length>0)
        {
            n.pop();
        }
        $("#spins").val(n)
        run(n)
    });

    $("#clean").click(function(){
        $("#spins").val("")
    });

    $("#run").click(function(){
        var n = GetUserNumbers();
        run(n)
    });

});
// ---------------------------------------------------------------
// --------------------- FUNCTIONS -------------------------------
// ---------------------------------------------------------------

function run(n)
{

    $("#alert").text("")

    // Evens
    var conditions = ['color[n] == "red"','color[n] == "black"','n%2 == 0 && n<37','n%2 == 1 && n<37','n > 18 && n<37','n < 19 && n>0']
    var checklocation = ['Red','Black','Even','Odd','High','Low']
    var idWins = "#evenwin"
    var idLosses = "#evenloss"

    checkCondition(n, conditions, checklocation, idWins, idLosses)

    // Dozens
    var conditions = ['n%3 == 1','n%3 == 2','n%3 == 0','n>=1 && n<=12','n>=13 && n<=24','n>=25 && n<=36']
    var checklocation = ['Row 1 [1,2,3..]','Row 2 [2,3,4..]','Row 2 [3,6,9..]','Dozen 1 [1-12]','Dozen 1 [13-24]','Dozen 1 [25-36]']
    var idWins = "#dozenwin"
    var idLosses = "#dozenloss"

    checkCondition(n, conditions, checklocation, idWins, idLosses)
}

function checkCondition(n, conditions, checklocation, idWins, idLosses)
{
    for(var i=0; i<conditions.length; i++)
    {
        var check = function(n){ if(conditions[i]){ return true; } else { return false; }}
        var wins = checkWins(n, check)
        var losses = checkLosses(n, check)
        if(wins >= $(idWins).val()) { $("#alert").text($("#alert").text()+" "+checklocation[i]+" loses "+wins+" times in a rows.<br/>")}
        if(losses >= $(idLosses).val()) { $("#alert").text($("#alert").text()+" "+checklocation[i]+" loses "+losses+" times in a rows.<br/>")}
    }
}

function checkWins(n, condition)
{
    var wins = parseInt(0);
    for(var i=0;i<n.length;i++)
    {
        if(condition(n[i]))
        {
            wins += 1 
        }
        else
        {
            wins = 0
        }   
    }

    return wins 
}

function checkLosses(n, condition)
{
    var losses = parseInt(0);
    for(var i=0;i<n.length;i++)
    {
        if(condition(n[i]))
        {
            losses = 0
        }
        else
        {
            losses += 1
        }
    }
    return losses
}

$.fn.multiline = function(text){
    this.text(text);
    this.html(this.html().replace(/\n/g,'<br/>'));
    return this;
}


function getWheel()
{
    if($("input[name=wheel]:checked").val()=="0")
    {
        wheel = wheel0
    }
    else
    {
        wheel = wheel00
    }
    color = GetColor(wheel)
}

function reset()
{
    evenwins = parseInt(0);
}
function GetUserNumbers()
{
    var n = $("#spins").val().split(",");

    for(var x=0; x<n.length; x++)
    {
        if(n[x].trim() == "0")
        {
            n[x] = "37";
        }
        if(n[x].trim() == "00")
        {
            n[x] = "38";
        }
        n[x] = parseInt(n[x].trim());
    }
    return n;
}

function GetColor(wheel)
{
    var color = Array();
    if(wheel.length==37)
    {
        color[1] = "red";
        color[2] = "black";
        color[3] = "red";
        color[4] = "black";
        color[5] = "red";
        color[6] = "black";
        color[7] = "red";
        color[8] = "black";
        color[9] = "red";
        color[10] = "black";
        color[11] = "black";
        color[12] = "red";
        color[13] = "black";
        color[14] = "red";
        color[15] = "black";
        color[16] = "red";
        color[17] = "black";
        color[18] = "red";
        color[19] = "red";
        color[20] = "black";
        color[21] = "red";
        color[22] = "black";
        color[23] = "red";
        color[24] = "black";
        color[25] = "red";
        color[26] = "black";
        color[27] = "red";
        color[28] = "black";
        color[29] = "black";
        color[30] = "red";
        color[31] = "black";
        color[32] = "red";
        color[33] = "black";
        color[34] = "red";
        color[35] = "black";
        color[36] = "red";
        color[37] = "green";
    }
    if(wheel.length==38)
    {
        color[1] = "red";
        color[2] = "black";
        color[3] = "red";
        color[4] = "black";
        color[5] = "red";
        color[6] = "black";
        color[7] = "red";
        color[8] = "black";
        color[9] = "red";
        color[10] = "black";
        color[11] = "black";
        color[12] = "red";
        color[13] = "black";
        color[14] = "red";
        color[15] = "black";
        color[16] = "red";
        color[17] = "black";
        color[18] = "red";
        color[19] = "red";
        color[20] = "black";
        color[21] = "red";
        color[22] = "black";
        color[23] = "red";
        color[24] = "black";
        color[25] = "red";
        color[26] = "black";
        color[27] = "red";
        color[28] = "black";
        color[29] = "black";
        color[30] = "red";
        color[31] = "black";
        color[32] = "red";
        color[33] = "black";
        color[34] = "red";
        color[35] = "black";
        color[36] = "red";
        color[37] = "green";
        color[38] = "green";
    }
    return color;
}

</script>
</head>
<body>
Toggle Displays</br><br/>
<div >
<button class="bntshow" id="enterSpins">Enter Spins</button><br/>
<button class="bntshow" id="setAlert">Set Alerts</button><br/>
<button class="bntshow" id="howTo">How To</button><br/>
<input type="radio" name="wheel" value="0">0 Wheel<br/>
<input type="radio" name="wheel" value="00" checked>00 Wheel<br/>
</div><br/>
<div id="alert"></div>
<hr>


<!-- Enter Spins -->
<span class="spanhide" id="divSpins">
<button class="bntcaladd" id="enterPad">Toggle Numberpad</button><br/>
<br/>

<span class="spanhide" id='showSpinsPad'>
<br/>
<button class="bntcal" id="calculator" value="0">0</button>
<button class="bntcal" id="calculator" value="00">00</button><br/>
<button class="bntcal" id="calculator" value="1">1</button>
<button class="bntcal" id="calculator" value="2">2</button>
<button class="bntcal" id="calculator" value="3">3</button><br/>
<button class="bntcal" id="calculator" value="4">4</button>
<button class="bntcal" id="calculator" value="5">5</button>
<button class="bntcal" id="calculator" value="6">6</button><br/>
<button class="bntcal" id="calculator" value="7">7</button>
<button class="bntcal" id="calculator" value="8">8</button>
<button class="bntcal" id="calculator" value="9">9</button><br/>
<button class="bntcaladd" id="clear">Clear</button>
<button class="bntcaladd" id="add">ADD</button><span id="currentSpin"></span>
<br/>
<button class="bntcaladd" id="undo">Undo</button><br/>
<span id="currentSpin"></span>
<br/>
</span>
<span id="clearBox">Enter roulette numbers separated by a comma</span><br/>
<textarea rows="10" cols="50" id="spins"></textarea><br/><br/>
<span id="clearBox1">
<button id="clean">Clear Box</button>
<button id="run">Run</button>
</span>

</span>

<!-- Set Alerts -->
<span class="spanhide" id="divAlerts">
<h2>Evens</h2>
<input type="text" id="evenwin" value="2"> Wins in a row<br>
<input type="text" id="evenloss" value="6"> Losses in a row<br>
<br><br>
<h2>Dozens</h2>
<input type="text" id="dozenwin" value="6"> Wins in a row<br>
<input type="text" id="dozenloss" value="6"> Losses in a row<br>
<br><br>

</span>

<!-- How To -->
<span class="spanhide" id="divHowTo">
How To
</span>


</body>
</html>

Yes, absolutely! 是的,一点没错!

In JavaScript, you are capable of saving functions to variables, and hence pass them around as parameters; 在JavaScript中,您可以将函数保存到变量,然后将它们作为参数传递; this is one of the most powerful aspects of JavaScript. 这是JavaScript最强大的方面之一。 So for example, if you want to check if the color is red, you can write a condition test function that returns true/false as follows: 因此,例如,如果要检查颜色是否为红色,则可以编写条件测试函数,该函数返回true / false,如下所示:

var checkColor = function(nElement){
      var color = color(nElement);
      if(color == 'red'){
          return true;
      }
      else if(color == 'black'){
           return false;
      }
 }

So now, you have a variable checkColor that is a function that checks if a color is red or not. 因此,现在,您有了一个变量checkColor ,该函数可以检查颜色是否为红色。 Now, you can pass this function into your test function like this: 现在,您可以像下面这样将该函数传递到您的test函数中:

function test(n,testFunc)
{
var wins = parseInt(0);
var losses = parseInt(0);

for(var i=0;i<n.length;i++)
{
    if(testFunc(n[i])) //testFunc = checkColor in this case since we passed in checkColor
    {
        wins += 1 
        losses = 0
    }
    else
    {
        wins = 0
        losses += 1
    }

}

test(n,checkColor); //This is where you pass in checkColor as your test func

And so for example, if we wanted to add another test for an even, we could write a function as so: 因此,例如,如果我们想为偶数添加另一个测试,则可以这样编写一个函数:

var checkEven = function(nElement){
     if(nElement % 2 == 0){
           return true;
     }
     else{
           return false;
     }
 }

And we could simply run test using this new condition like: 我们可以使用以下新条件简单地运行test

test(n,checkEven);

And so from here, you should get the idea of how to create a test function and pass it into a universal test function. 因此,从这里开始,您应该了解如何创建测试功能并将其传递给通用测试功能。 If you need clarification, don't hesitate to ask! 如果您需要澄清,请随时询问!

Simply pass the condition as function.只需将条件传递为 function。

Javascript: Javascript:

const myFunctionByCondition = (conditionFn) => {
   const index = 10

   if (conditionFn(index)) return "Condition applies"
   return "Condition does not apply"
}

const val = myFunctionByCondition(i => i >= 10)

Typescript: Typescript:

const myFunctionByCondition = (conditionFn: (i: number) => boolean) => {
   const index = 10

   if (conditionFn(index)) return "Condition applies"
   return "Condition does not apply"
}

const val = myFunctionByCondition(i => i >= 10)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript:如何创建一个函数 1. 接受一个全局变量作为参数 2. 改变该全局变量的值? - Javascript: How can I create a function that 1. accepts a global variable as a parameter 2. alters the value of that global variable? 如果分配给它的新值满足 javascript 中的预定义条件,我如何创建一个只能更改其值的变量? - How can I create a variable that can only change its value if the new value to be assigned to it meets a predefined condition in javascript? Javascript'Array'和'Loop'如何“变量[i]”成为一个条件 - Javascript ' Array ' and ' Loop ' how can “ variable[i] ” be a CONDITION Javascript Calculator:如何根据条件创建操作员按钮? - Javascript Calculator: How can I create an operator button based on a condition? 如何在不使用参数的情况下在javascript中传递变量? - How can I pass variable in javascript without using parameter? 如何在JavaScript中连接字符串和变量以创建新变量? - How can i join a string and a variable to create a new variable in javascript? 在JavaScript中,如何创建一个带有可选参数的function? - In JavaScript, how can I create a function with an optional parameter? 如何为 javascript 中的inquirer.prompt 问题的答案创建 function 参数(变量)? MySQL也参与 - How do I create a function parameter (variable) for the answers to an inquirer.prompt question in javascript? MySQL is also involved 我可以在javascript中创建对变量的引用吗? - Can I create a reference to a variable in javascript? 如何在用作参数的函数中使用Javascript设置局部变量? - How can i set a local Variable in Javascript in a function i used as parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM