0

here's my code, I was trying to print the price property of worker and soldier objects

var army = [worker, soldier];

var worker={
	name:'Worker',
	price : 10,
	ammount : 0,
	award:0,
	//award : 5/11,
	time : 1000,
	defense: 10,
	attack: 5
}

var soldier={
	name:'Soldier',
	price : 50,
	ammount : 0,
	award:0,
	//award : 0.75,
	time : 1000,
	defense: 30,
	attack: 15
}

for (var i=0; i<army.length; i++){
	alert(this.price);
}

Do you have any idea how can I get into price property of these objects?

1
  • console.log(this) will show you why it does not work. It should be army[i].price Commented Jul 10, 2015 at 19:15

2 Answers 2

1

You are assigning undefined variables to the army array, before the objects are initialized. Move that first line to after the worker and soldier.

Also, the variable this in a for-loop doesn't refer to anything. Use army[i] instead, or you could assign var this = army[i];.

var worker = {
  name: 'Worker',
  price: 10,
  ammount: 0,
  award: 0,
  //award : 5/11,
  time: 1000,
  defense: 10,
  attack: 5
}

var soldier = {
  name: 'Soldier',
  price: 50,
  ammount: 0,
  award: 0,
  //award : 0.75,
  time: 1000,
  defense: 30,
  attack: 15
}

var army = [worker, soldier];

for (var i = 0; i < army.length; i++) {
  alert(army[i].price);
}

Sign up to request clarification or add additional context in comments.

Comments

0

Define the army array after you create the other arrays:

var army = [worker, soldier];

Then use army[i] to get the price from each object:

for (var i=0; i<army.length; i++){
    alert(army[i].price);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.