2

As we know the index of $.each will start from zero. I want to print the index from 1 to 10, as I have 10 array.

$.each(myArr, function(i){
console.log(i++);
}

why is it I'm getting from 0 still?

Alice Xu
  • 533
  • 6
  • 20

4 Answers4

1

Try this.

$.each(myArr, function(i){
console.log(++i);
})

This is a difference between prefix and postfix operator. Prefix operator increases the value after the current operation is done. Postfix operator increases the value first and executes the current statement. This above code is for just explaining things.

As @Ghazgkull suggested, it is better to use i+1 which conveys the indent of the code.

Manikandan
  • 3,025
  • 2
  • 19
  • 28
0

The ++ operator AFTER the variable increases that variable after the current call is finished (in your case, after the console log call), which is why you see it starting from 0.

Since it's an index, there's no need for you to manually increase its value, but a simple console.log(i+1); would work just fine.

Otherwise, you can increase it BEFORE the current call, by putting ++ before the variable, as @Satya said in the comments.


See it here:

var myArr = [1,1,1,1,1,1,1,1,1,1];

$.each(myArr, function(i){
  console.log(i+1);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Shomz
  • 37,421
  • 4
  • 57
  • 85
0

When the ++ operator is applied on the right side of the variable (i++), the current value before incrementing is used. You should use ++i if you want to get the value after incrementing.

Mike G
  • 668
  • 1
  • 6
  • 17
0

$.each() increments the value for you. You don't need to increment it yourself. Your code should be:

$.each(myArr, function(i) {
    console.log(i + 1);
}

Even if ++i works in this case, you shouldn't use an incrementor here. To any experienced programmer, it will look like you're trying to increment a value in a way that doesn't make sense. Using i + 1 makes it clear that you're simply computing a value.

Ghazgkull
  • 970
  • 1
  • 6
  • 17