I've create an array in Javascript designed to hold basic details about a set of upgrades as part of a game I'm making. The upgrades are defined as follows;
var Upgrade = {Name:NameIn,
Description:DescriptionIn,
Image:ImageIn,
Purchased:0,
Visible:false,
ID:IDIn}
I've got a standard for loop that is trying to access these variables. Yet for some reason the Description variable comes up with an "undefined" error when I try to access it using the i variable I've created as part of the loop. i.e. Upgrades[i].Description
comes up as undefined.
I've checked and all of the other elements such as Name, Image etc can be accessed using the "i" variable. e.g. Upgrades[i].Name
Yet if I manually type in what i is equal to as part of my code at the time I try to access Description (e.g having Upgrades[1]
as oppose to Upgrades[i]
) it allows access to it.
The array is filled as such;
function AddUpgrade(NameIn,DescriptionIn,ImageIn,IDIn){
var Upgrade = {Name:NameIn,
Description:DescriptionIn,
Image:ImageIn,
Purchased:0,
Visible:false,
ID:IDIn}
Upgrades.push(Upgrade);
AddUpgrade("Sharpened Rocks","Description",
"img/upgrades/Caveman2.png","Caveman2Display");
Below is the loop that is trying to access the variables to send to an HTML document;
for (i = 1; i < Upgrades.length ; i++){
if (Upgrades[i].Visible == 1){
document.getElementById("upgrades").innerHTML += "<div class=\"upgrade\" id=\"" + Upgrades[i].ID +
"\" onclick=\"ButtonBuyUpgrade(" + i + ")\"><img src=\"" + Upgrades[i].Image + "\"><div class=\"hovertext\" id=\""
+ Upgrades[i].ID + "Hover\">" + DisplayUpgradeCost(i) + Upgrades[i].Description + "</div></div>";
}
}
Here is the output from console;
Uncaught TypeError: Cannot read property 'Description' of undefined inc.js:161 DisplayUpgrade inc.js:161 CalculateUnlocks inc.js:463 (anonymous function) inc.js:502 Object {Name: "Sharpened Rocks", Description: "Description", Image: "img/upgrades/Caveman2.png", Purchased: 0, Visible: 1…} Description: "Description" ID: "Caveman2Display" Image: "img/upgrades/Caveman2.png" Name: "Sharpened Rocks" Purchased: 0 Visible: 1
And here is the console.dir output;
1: Object Description: "Description" ID: "Caveman2Display" Image: "img/upgrades/Caveman2.png" Name: "Sharpened Rocks" Purchased: 0 Visible: 1
All the other elements are also filled in, there are no missing pieces of information.
I'm completely confused by this and have no idea why it's happening. Any thoughts?
for
loops:for(;;)
andfor( in )
. Which are you using. The object you posted here might well end up having a member calledDescription
with the valueundefined
. It all depends on what the value ofDescriptionIn
was when the object was created... – Elias Van Ootegem Aug 20 '14 at 12:00console.log(Upgrades)
orconsole.log(Upgrades[i])
in your loop. – parchment Aug 20 '14 at 12:00console.dir
your array before the loop and see if there are any holes. – Felix Kling Aug 20 '14 at 14:49