Sorry about the shoddy title of this question - I really can't describe the problem any more succinctly!
I can't figure out what's happening in my code! I have an object which looks like this:
var fruits = {name: "bananas", quantity: "3"}
And an quantity input field (#qty) whose value is (let's say) 2.
console.log(fruits);
alert(fruits[0].quantity); //outputs 3
fruits[0].quantity = Number(fruits[0].quantity) + Number($("#qty").val());
alert(fruits[0].quantity); //outputs 5
The problem is that after all of this runs, when I go into the console to inspect the output of console.log(fruits);, the console shows {name: "bananas", quantity: 5}.
P.S. Notice the added quantity and lack of quotation marks!
Any ideas what's happening?
fruits[0]? You don't have an array or a property called0. Your code shouldn't run at all (but if it did, the output would be correct, wouldn't it?).alert(fruits[0].quantity); //outputs 3— no, it throws an exception because you are trying to readquantityof an undefined value. Show us a real minimal reproducible examplefruits[0]rather thanfruitsis that when omit the[0]I receiveundefinedandNaNas myalert()s. @Quentin, not sure why you think its an undefined value... But yes, it looks like your duplicate suggestion is the answer. The suggestion there was to console.log a copy of the variable, rather than the variable itself, as the variable is manipulated (added) before the console actually logs it, which is why when it finally gets to logging it, it displays the added values.