使用javascript在计算中未定义

时间:2018-01-12 17:22:57

标签: javascript

每次我运行这段代码(var水平速度是一个数字,由用户用表格插入)我得到单词undefined后跟文本execute @e [type ... etc. 我不希望输出中的单词undefined,因为它也出现在textarea中。我的代码中有什么错误会导致单词出现?

www.example.com/directory/ABCDEF/pagename
www.example.com/directory/BCDEFG/pagename
www.example.com/directory/CDEFGH/pagename
www.example.com/directory/DEFGHI/pagename

1 个答案:

答案 0 :(得分:3)

问题在于:

var output = output + add_z_position;

在第一次传递时,output以前从未被分配过值,因此它有undefined

var部分移到循环上方并给它一个初始值,可能是""

function command() {
    var form = document.getElementById("form");
    var horizontal_speed = form.elements["horizontal_speed"].value;
    var output = "";
    for (var i = 1; i <= horizontal_speed; i++) {
        var standard_command = "execute @e[type=armor_stand,name=test] ~ ~ ~ /setblock etc particle insert_particle ~x_position ~1 ~z_position 0 0 0 0.01 1 force"
        var rad = (2 * i * Math.PI) / horizontal_speed;
        var x_position = Math.round(Math.cos(rad) * 100) / 100;
        var z_position = Math.round(Math.sin(rad) * 100) / 100;

        var add_x_position = standard_command.replace('x_position', x_position);
        var add_z_position = add_x_position.replace('z_position', z_position);
        output = output + add_z_position;
    }
    document.getElementById('output').value = output;
}

另外,

output = output + add_z_position;

可以

output += add_z_position;

如果你愿意的话。