Skip to main content
brucegray
Participant
January 30, 2018
Answered

Stop push from overwriting values in an array

  • January 30, 2018
  • 1 reply
  • 7676 views

Hi,

I'm trying to create an array containing scores and usernames which I can then sort and display in a table, but I'm stuck on one issue. When I try to push a second score to the highscores array, it saves again at position 0 rather than adding new data to position 1 and so on. In the following code, myScore contains the score that the user just achieves and myName contains their set username.

var highscores:Array = new Array();
highscores
.push({score: myScore, player: myName});
highscores
.sortOn("score", Array.DESCENDING | Array.NUMERIC);

for (var i:int = 0; i < highscores.length; i++)
{
  trace
(highscores[i].score, highscores[i].player);
}

How can I get this to add to the array rather than overwriting current data?

Thanks.

This topic has been closed for replies.
Correct answer JoãoCésar17023019

Hi!

Do you always call the new Array() line when you want to update the array? Because if you do this, the push method will always find an empty array.

1 reply

JoãoCésar17023019
Community Expert
JoãoCésar17023019Community ExpertCorrect answer
Community Expert
January 30, 2018

Hi!

Do you always call the new Array() line when you want to update the array? Because if you do this, the push method will always find an empty array.

brucegray
brucegrayAuthor
Participant
January 30, 2018

This was the issue, not sure how I missed that.

Many thanks!

JoãoCésar17023019
Community Expert
Community Expert
January 30, 2018

It happens all the time! No worries.

And you're welcome!