0
我對JS很新,而且我的代碼存在一個問題,我真的不明白:我嘗試將一個文本值對添加到數組,基本上它可以工作,但不是附加一對,而是附加兩對。下面是代碼片段,問題在後面的if語句中。我在片段中添加了評論,以解釋我正在做的事情。JavaScript:爲什麼array.push()追加兩個對象而不是一個
players.addResult = function(result){
//result-argument contains results of games, like: Object {0: "4-2", 1: "5-3", 2: "7-1"}
var playerList = [];
var standingArray = [];
resultLen = Object.keys(result).length;
//loop iterates thru results by index
for (var x=0; x < resultLen; x++) {
var newResult = result[x];
newResult = newResult.split("-");
if (newResult[0] > newResult[1]) {
//the next line retrieves the name of a winning player from another array
playerVal = players.pairs[x].player1;
playerVal = playerVal.text;
console.log(playerVal); //Output of this: Bill
value = playerList.indexOf(playerVal); // Checks if the player already exists on the standings, returns -1 if false.
if (value === -1) {
/*if the player gets his first points, his name and earned
points are added on to the standingArray. And the next line of code is the
interesting one, because I am expecting to have an array with
index, name of the winner and points. Like this:
Object 0 name:"Bill" points:2. But instead of that, there are two
objects on the array, one for both players:
[Object]
0: Object
name: "Bill"
points: 2
__proto__: Object
1: Object
name: "Greg"
points: 2
__proto__: Object
length: 2
__proto__: Array[0]*/
standingArray.push({name: playerVal, points: 2})
playerList.push(playerVal); //this is for keeping on track that player is now on the standingArray
console.log(playerVal);
console.log(playerList);
console.log(standingArray);
}
else {
console.log("else");
}
console.log(playerList);
console.log(standingArray);
所以現在的問題是,JS如何獲取Greg的名字 - 我已經檢查了playerVal變量,它真的只包含比爾的名字。任何幫助熱烈歡迎!
檢查'players.pairs'陣列,也許格雷格贏了一場比賽,和比爾贏得另一 –