Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjohn larson
16,594 PointsTrying to store values from the calculator object into an array but...I don't quite have it.
It's all in the console. It looks to me like I should be able to store calculator.equals() by pushing it into calculatorArray. But when I run calculatorArray in the console I get 0. Any thoughts?
var calculator = {
sum: 0,
add: function(value){
this.sum += value;
},
clear: function(){
this.sum = 0;
},
equals: function(){
return this.sum;
}
}
var calculatorArray = [];
calculatorArray.push(calculator.equals())
2 Answers
Jennifer Nordell
Treehouse TeacherHi there! But sum is zero. And that's what's being pushed to the array You haven't used add to add anything to the original sum value which is equal to 0. I've added a few lines of code to yours so you can see more clearly what's going on. Take a look:
var calculator = {
sum: 0,
add: function(value){
this.sum += value;
},
clear: function(){
this.sum = 0;
},
equals: function(){
return this.sum;
}
}
calculator.add(2);
calculator.add(7);
var calculatorArray = [];
calculatorArray.push(calculator.equals());
console.log(calculatorArray[0]);
Hope this helps!
Tommaso Poletti
5,205 PointsI think i understand your problem :) The problem is if u put the ".push" method away from the function inside an object the code run one time and that array doesn't update.
so... if u write
var calculatorArray = [];
var calculator = {
sum: 0,
add: function(value){
calculatorArray.push(value);
this.sum += value;
},
clear: function(){
this.sum = 0;
},
equals: function(){
console.log(calculatorArray);
return this.sum;
}
}
When you add a number to the sum the ".push" method add in the array the number you want
and if u check with calculator.equals the function log in the console the array and the total :)
john larson
16,594 Pointsjohn larson
16,594 PointsI haven't tried it yet, but looking at this i realized: the lines that you added, I have been running this in the console. Therefore, I probably should have run the calculatorArray.push(calculator.equals()) in the console as well. Now I'll go try it. Thanks.