将对象推入数组会产生相同的值

Pushing object to array results in same value

我有以下 javascript 代码无法正常工作。我有一个复选框列表,其中两个项目是 "TestDuration" 和 "AssessmentScores"。我正在尝试遍历列表(工作正常)并将检查的值添加到数组中。

var SAIndex = 0;
var SSIndex = 0;
var ScoresIndex = 0;
var SubAssessments = [];
var SubAssessmentScores = [];

//Get to the container element
var SSList = document.getElementById("islSubAssessmentScore_container");  

//turn it into an array of the checkbox inputs
SSList = SSList.getElementsByTagName("input"); 

//create a temporary object to store my values
var tempPair = new Object(); 

//iterate through the checkbox lists
for(var i = 1; i < SSList.length;i++) 
{
    //if the value is checked add it to the array
    if (SSList[i].checked) 
    {
        var P = SubAssessments[SAIndex];
        var V = SSList[i].value;
        //tempPair.Parent = SubAssessments[SAIndex];
        tempPair.Parent = P;
        //tempPair.Value = SSList[i].value;
        tempPair.Value = V;
        //show me the values as they exist on the page
        alert(tempPair.Parent + "|" + tempPair.Value); 
        SubAssessmentScores.push(tempPair);

        //show me the values I just added to the array
        alert(SubAssessmentScores.length-1 + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Parent + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Value); 

        //uncheck the values so when I refresh that section of the page the list is empty
        SSList[i].checked = false; 
    }
}

//output the list of objects I just created
for (i = 0;i < SubAssessmentScores.length;i++) 
    alert(i + "|" + SubAssessmentScores[i].Parent + "|" + SubAssessmentScores[i].Value)

现在发生的事情是,当我遍历列表时,我收到以下警报:
-第一关-

StudentID|TestDuration
0|StudentID|TestDuration

-二传-

StudentID|AssessmentScores
1|StudentID|AssessmentScores

这是我希望输出的...但是在代码片段的末尾,当它运行 for 循环以吐出所有值时,我收到以下警报...

0|StudentID|AssessmentScores
1|StudentID|AssessmentScores

我一辈子都弄不明白为什么要用第二个值替换第一个值。我认为它可能使用了一个参考变量,这就是为什么我添加了 P 和 V 变量来尝试解决这个问题,如果是这样的话,但结果是一样的。

这是因为您在循环的每次迭代中都添加了相同的变量。

尝试像这样更改您的推送:

SubAssessmentScores.push({
  Parent: P,
  Value: V
});

也就是说,我建议你多学习一点 javascript 和语言中的约定,例如你的变量命名不受欢迎,因为你应该只在构造函数的名称开头使用大写字母.

一本好书是 Javascript Douglas Crockford 的精彩部分。