数字组合计算

Number combination calculating

我有一个任务需要生成从 0-0-0 到 100-100-100 (x,y,z)

var x = 0

var y = 0

var z = 0

while(true){
x++
while(true){
    y++
    while(true){
       z++
       msg.payload = [x,y,z]
       node.send(msg)
        }}}

我遇到的问题是 x 和 y 值永远不会改变(输入时只有一次)... 我认为这不是一种有效的方法,有什么建议吗?

如果知道迭代次数,使用 for 循环会更简单:

for (let x = 0; x <= 100; ++x) {
    for (let y = 0; y <= 100; ++y) {
        for (let z = 0; z <= 100; ++z) {
            msg.payload = [x,y,z]
            node.send(msg)
        }
    }
}

for (let x = 0; x <= 3; ++x) {
    for (let y = 0; y <= 3; ++y) {
        for (let z = 0; z <= 3; ++z) {
            // msg.payload = [x,y,z]
            // node.send(msg)
            console.log({ payload: [x, y, z] });
        }
    }
}

当然,您可以使用 while 循环代替,但您必须记住在 100 次迭代后中断:

let x = 0;
while(true) {
    let y = 0;
    while(true) {
        let z = 0;
        while(true) {
            msg.payload = [x,y,z]
            node.send(msg);
            if (z === 100) break;
            z++;
        }
        if (y === 100) break;
        y++;
    }
    if (x === 100) break;
    x++;
}

let x = 0;
while(true) {
    let y = 0;
    while(true) {
        let z = 0;
        while(true) {
            // msg.payload = [x,y,z]
            // node.send(msg);
            console.log({ payload: [x, y, z] });
            if (z === 3) break;
            z++;
        }
        if (y === 3) break;
        y++;
    }
    if (x === 3) break;
    x++;
}

或者你对while条件使用倒置中断条件:

let x = 0;
while(x <= 100) {
    let y = 0;
    while(y <= 100) {
        let z = 0;
        while(z <= 100) {
            msg.payload = [x,y,z]
            node.send(msg);
            z++;
        }
        y++;
    }
    x++;
}

let x = 0;
while(x <= 3) {
    let y = 0;
    while(y <= 3) {
        let z = 0;
        while(z <= 3) {
            // msg.payload = [x,y,z]
            // node.send(msg);
            console.log({ payload: [x, y, z] });
            z++;
        }
        y++;
    }
    x++;
}