无法更改数组中的值

时间:2017-01-11 20:33:51

标签: javascript arrays

我是编程和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,因为只将其直接分配给索引中的变量似乎有效。

4 个答案:

答案 0 :(得分:2)

看起来你的代码期望在数组索引处更新faces时更新变量,但faces[1] = 5将值5赋给faces[1],替换值( 0)最初是从f1复制的。再次尝试,仅使用索引,但这次将警报更改为:

alert("faces are: " + faces.join(','));

另外,正如@StephenQuan指出的那样,你需要为内循环使用不同的索引变量

答案 1 :(得分:1)

您不会更改fx的值,因为它们是简单的数据类型(int),它们是called by value。简单类型不是对象,可以是called by reference。请参阅此问题:Is JavaScript a pass-by-reference or pass-by-value language?

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

for(var i = 0; i < 6; i++){
  faces[i] = faces[i] + 5;//doesn't add anything
  faces[2] = faces[2] + 5; //nor does this
  faces[1] = faces[1]++; //or this
  f1 = 3; //this works however
}
console.log("faces are: " + f1 + ", " + f2 + ", " + f3 + ", " + f4 + ", " + f5 + ", " + f6);
console.log("faces are:" , faces);

答案 2 :(得分:0)

请参阅var hoisting部分。您在内部循环和外部循环中使用var i。改变它,看它是否有助于流动。如果您使用ECMA 6,我建议尽可能使用let代替var

答案 3 :(得分:0)

这是因为您将对象的引用传递给数组。当你第一次初始化数组时。

在循环中你正在执行

faces[i] = 5

您正在将对象f1的引用替换为值5。

请尝试以下操作。

faces = [{value: 0}, {value: 0}, {value: 0}, {value: 0}, {value: 0}, {value: 0}];

faces[i].value = 5;

alert("faces are: " + face[0].value+ ", " + face[1].value+ ", " + face[2].value+ ", " + face[3].value+ ", " + face[4].value+ ", " + face[5].value);