Here’s my code:
var array = [{"number":"500","title":"whatever 500"},{"number":"400","title":"whatever 400"}];
alert(array[0].number); //should output 500
$.each(array, function(index, val)
{
array[index].number = val * 5;
});
alert(array[0].number); //should output 2500
I’m trying to multiply all the numbers in my array by 5. But for some reason it’s not working. It outputs NaN (Not-a-Number). And when I try to add 50, it outputs [object Object]50.
Can someone please tell me what I’m doing wrong here?
The problem is that
valis the object, not a specific value from it. So you’re trying to multiply{"number":"500","title":"whatever 500"}by5, which unsurprisingly doesn’t work.You can just use
thisto refer to the current element in the loop. Your code might look like this:You could, in fact, make this even shorter, by using the
*=assignment operator: