Reputation:
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?
Upvotes: 2
Views: 72
Reputation: 26291
Here is correct each
:
$.each(array, function(index, val)
{
array[index].number = val.number * 5;
});
You're iterating over the objects in array, because array
contains objects. First val
in your example equals to {"number":"500","title":"whatever 500"}
Upvotes: 1
Reputation: 603
"500" is not a number (NaN), it's a string.
Try with this array :
var array = [{"number":500,"title":"whatever 500"},{"number":400,"title":"whatever 400"];
Upvotes: -2
Reputation: 237817
The problem is that val
is the object, not a specific value from it. So you're trying to multiply {"number":"500","title":"whatever 500"}
by 5
, which unsurprisingly doesn't work.
You can just use this
to refer to the current element in the loop. Your code might look like this:
$.each(array, function() {
this.number = this.number * 5;
});
You could, in fact, make this even shorter, by using the *=
assignment operator:
$.each(array, function() {
this.number *= 5;
});
Upvotes: 2