3

I'm trying to manipulate the properties in an object like this:

for (property in posts.data) {
    property = property+1+",";
    output += property;
}
document.write(output);

The properties are numerical: 0, 1, 2 etc.

I want to get the result 1,2,3 in this case. But instead I get 01,11,21, etc... It seems to treat the property as a text-string rather than a number. Why? And what can I do about it?

Francois
  • 2,005
  • 21
  • 39
Himmators
  • 14,278
  • 36
  • 132
  • 223

4 Answers4

5

1.Unary '+' operator converts a string into an integer

for (property in posts.data) {
   var t = +property + 1;
   output += t+",";
}

2.Javascript's parseInt method

for (property in posts.data) {
    var t = parseInt(property, 10)+ 1;
     output += t+","; 
}

The second argument in the parseInt function call(radix) will tell the function what numeric system to follow.

Ashwin Krishnamurthy
  • 3,750
  • 3
  • 27
  • 49
1

Use parseInt to convert the property to integer before adding 1 into it.

Demo: http://jsfiddle.net/mPSnL/

codef0rmer
  • 10,284
  • 9
  • 53
  • 76
1

Parse the property variable in Int. like parseInt()

for (property in posts.data) {
    var p = parseInt(property)+1+",";
    output += p;
 }
Talha
  • 18,898
  • 8
  • 49
  • 66
1

You could force the string to and int

for (property in posts.data) {
  var v = parseInt(property, 10) + 1;
  output += v + ",";
}
tjp
  • 144
  • 6
leonm
  • 6,454
  • 30
  • 38