谁能告诉我为什么所有 object.num 都打印为 1?这让我发疯。无论如何,for 循环后 object.num = 1 的值,即使它们从未设置为 1。请复制整个段以进行调试。
<script type="text/javascript">
window.addEventListener("load", main, false);
const n = 4;
function main()
{
var belt = new Array(4*n);
initArr(belt);
printIt(belt);
populateArr(belt);
printIt(belt);
reorder(belt);
printIt(belt);
}
function populateArr(arr)
{
var a = {name:"a", num:0};
var b = {name:"b", num:0};
var end = arr.length;
var i = end-1;
for(var temp = n; temp > 0; temp--)
{
a.num = temp;
arr[i] = a;
i-=2;
}
i = end-2;
for(var temp = n; temp > 0; temp--)
{
b.num = temp;
arr[i] = b;
i-=2;
}
return arr;
}
function printIt(arr)
{
var tempArr = new Array(arr.length);
for(var i=0; i < arr.length; i++)
{
tempArr[i] = arr[i].name + arr[i].num;
}
console.log(tempArr);
}
function initArr(arr)
{
var nothing = {name:null, num:0};
for(var i=0; i<arr.length; i++)
{
arr[i] = nothing;
}
return arr;
}
function reorder(arr)
{
var nothing = {name:null, num:0};
var counter = 0;
var aIndex = 0;
var bIndex = null;
for(var i=0; i < arr.length; i++)
{
if(arr[i].name === "b" && bIndex === null)//first b doesn't get moved
{
bIndex = i+1;
}
else if(arr[i].name === "a")
{
arr[aIndex] = arr[i];
arr[i] = nothing;
counter++;
aIndex++;
}
else if(arr[i].name ==="b")
{
arr[bIndex] = arr[i];
arr[i] = nothing;
counter++;
bIndex++;
}
}
console.log("count: " + counter);
console.log("n: " + n);
return arr;
}
</script>
最佳答案
Somehow after the for loop the values of the object.num = 1 no matter what, even though they are never set to 1.
是的,“他们”是——在这个循环的最后一次迭代中,“他们”被设置为 1:
for(var temp = n; temp > 0; temp--)
{
a.num = temp;
arr[i] = a;
i-=2;
}
当 temp
为 1 时,该循环的最后一次迭代。
现在,您实际上只有一个对象 - 您正在将数组的每个元素设置为对该对象的引用。这就是数组中所有值看起来都一样的原因。如果你想每次创建不同的对象,你应该使用:
for(var temp = n; temp > 0; temp--)
{
arr[i] = { name: "a", num: temp };
i -= 2;
}
关于javascript - 通过引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26944233/