在JS中使用for循环实现相同的操作

时间:2018-07-19 19:30:22

标签: javascript for-loop

我有下一行代码

var seats = []


    for (a = 0; a <= seatsNumFront; a++) {
        seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515"))
    }
    for (b = 0; b <= seatsNumFront; b++) {
        seats.push(new Seat((b * xPad) + 300, 100, 30, 30, id++, "B", b, "#998515"))
    }
    for (c = 0; c <= seatsNumFront; c++) {
        seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
    }

我想要实现那些行将根据我将定义的值执行。

例如: 我想为变量分配数字,并且只写这行一次,然后根据我的变量

执行它

所以可以说我会写:

var seats = []
var num = 3

    for (c = 0; c <= seatsNumFront; c++) {
        seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
    }

想要的结果:

var seats = []
var num = 3

for (a = 0; a <= seatsNumFront; a++) {
    seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515"))
}
for (b = 0; b <= seatsNumFront; b++) {
    seats.push(new Seat((b * xPad) + 300, 100, 30, 30, id++, "B", b, "#998515"))
}
for (c = 0; c <= seatsNumFront; c++) {
    seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
}

2 个答案:

答案 0 :(得分:1)

在这里我并没有完全得到您想要的东西,但是我知道您想编写一个函数。 这是示例代码,可以使用两个参数将for循环放入函数中。

编辑:根据您的阐述,我添加了更多代码。

//Variables in your code, dont worry about these.
var id = 0;  
var seatsNumFront = 1;
var seats = Array();
var xPad = 5

//Function to add seats based on the value (60,100,140 in your question) and a character ('A', 'B', 'C' in your question)
function addSeats(value, ch){
    for(var i = 0;i <= seatsNumFront;i++)
        seats.push(new Seat((i * xPad) + 300, value, 30, 30, id++, ch, i, "#998515"));   
}


var num = 3, start = 60, diff = 40, ch = 'A';
for(var i = 0;i < num;i++){
              //60 + (40 * i)
    addSeats(start + (diff * i),  ch++);
}
//The for-loop above will put seats in with the following parameters (60, 'A'), (100, 'B'), (140, 'C').

以上代码应适用于positive的任何num值。

答案 1 :(得分:1)

如果参数化了push语句,则可以根据需要传递值。 我使用了您的c forloop示例,并添加了一个开关盒。还有其他方法可以做到这一点,但关键是只编写一次for循环。

这是您可能希望实现的详细示例:

var num = 3
var param1 = 0;
var param2 = "";

for (x = 0; x <= seatsNumFront; x++) {
    switch (num) {
        case 1:
            param1 = 60;
            param2 = "A";
            break;
        case 2:
            param1 = 100;
            param2 = "B";
            break;
        case 3:
            param1 = 140;
            param2 = "C";
            break;
        default:
    }
    //seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))
    seats.push(new Seat((x * xPad) + 300, param1, 30, 30, id++, param2, x, "#998515"))
}

在此示例中,如果num等于3,则生成的for循环将与此过程相同:

seats.push(new Seat((c * xPad) + 300, 140, 30, 30, id++, "C", c, "#998515"))

通过将param1值设置为140并将param2值设置为“ C”。如果num等于2,那么它将分别使用100和“ B”。