我是编程和JavaScript的新手,无法通过其索引更改我的一个数组中的值。其余代码工作正常,但是我似乎无法通过其索引访问faces [],而在另一个数组中工作正常。

f1 = 0;
f2 = 0;
f3 = 0;
f4 = 0;
f5 = 0;
f6 = 0;
faces = [f1, f2, f3, f4, f5, f6];

//loop through a single throw with 5 dies
for(var i = 0; i < dice.length; i++){
    var die = Math.floor(Math.random() * 6) + 1;

    //if hold is true skip the corresponding iteration
    if(hold1 == true && i===0){
        alert("holding: " + held[0]);//shows the value of the die that's being held
        for(var i = 0; i < 6; i++){
            faces[i] = 5;//doesn't add anything
            faces[2] = 5; //nor does this
            faces[1]++; //or this
            f1 = 3; //this works however
        }
        alert("faces are: " + f1 + ", " + f2 + ", " + f3 + ", " + f4 + ", " + f5 + ", " + f6);
        continue;
    }
//rest of code


警报是检查值是否更改,并返回3、0、0、0、0、0,因为仅将其直接分配给索引中的变量似乎有效。

最佳答案

您不必更改fx的值,因为它们是简单的数据类型(int),它们是called by value。简单类型不是对象,可以是called by reference。看到以下问题:

关于javascript - 无法更改数组中的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41600199/

10-12 13:50