如何检查变量中是否有一个大于0

时间:2018-05-16 22:47:45

标签: javascript angular reactjs typescript

如何检查Typescript中给定变量的任何变量是否大于0

如何重写下面的代码,使其更加优雅/简洁?

public partial class Form1 : Form
{
    // EDIT - Become an array
    Invader[] monster = new Invader[5]; // Invader is the name of the class
    Random rand = new Random();
    PictureBox[] pb = new PictureBox[5];

    private void Spawner()
    {
        for (int i = 0; i < 5; i++)
        {
            this.monster[i] = new Invader(); // EDIT
            this.pb[i] = new PictureBox();
            this.pb[i].Name = "pb" + i.ToString();
            this.pb[i].Location = new Point(rand.Next(10, 300), monster.LocY);
            this.pb[i].BackgroundImageLayout = ImageLayout.Stretch;
            this.pb[i].BackgroundImage = Image.FromFile(@"Path");
            this.pb[i].BackColor = Color.Transparent;
            this.pb[i].Size = new System.Drawing.Size(40, 30);
            this.Controls.Add(this.pb[i]);
            this.pb[i].Click += this.Form1_Click;
            this.pb[i].Tag = i; // EDIT - Added tag assignation
        }
    }

    private void Form1_Click(object sender, EventArgs e)
    {
        PictureBox currentpicturebox = (PictureBox)sender;
        this.monster[(int)currentpicturebox.Tag].HealthDown(); // EDIT
        if (this.monster[(int)currentpicturebox.Tag].Health == 0) //EDIT
        {
            currentpicturebox.Dispose();
        }
    }

2 个答案:

答案 0 :(得分:5)

您可以将变量组合成一个数组,然后在其上运行some

return [a, b, c, d].some(item => item > 0)

答案 1 :(得分:3)

您可以将&&运算符与ternary operator结合使用,如下所示:

(a && b && c && d > 0) ? true : false // will return true if all integers are more than 0

jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/

或者您可以将变量分配给数组并使用Array.prototype.every(),如下所示:

let x = [a, b, c, d]

x.every(i => i > 0) // will return true if all integers are more than 0

jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/1/

或者为了使上述内容更短,您可以直接将值放在数组中并直接在数组上使用every,如下所示:

[0, 1, 0, 0].every(i => i > 0); // will return false since all integers are not more than 0

jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/3/

或者你可以创建一个可重复使用的函数,并且只需要一行就可以多次运行它:

function moreThanOne(...args){
   // Insert any of the above approaches here but reference the variables/array with the word 'arg'
}

moreThanOne(3,1,2,0); // will return false as well as alert false

moreThanOne(3,1,2,4); // will return true as well as alert true

jsFiddle: https://jsfiddle.net/AndrewL64/6bk1bs0w/2/

相关问题