I want to increment a value in a array when a link is pressed in JavaScript
i Used the following code
<script type="text/javascript">
var i=0;
var numbers = new Array();
function go(val){
numbers[i]=val;
i++;
alert(numbers[i]);
}
</script>
Called the Function like this
<a href='javascript:go(1)' </a>
but always the alert prompts me 'undefined'
The increment operator ( ++ ) increments (adds one to) its operand and returns the value before or after the increment, depending on where the operator is placed.
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.
The Prefix Operator ++i is called a prefix operator. This means that the value of the variable is incremented before it is used in the expression. For example, consider the following code: let i = 0;console.log(++i); // Prints 1console.log(i); // Prints 1.
The alert is correct -- before you do your alert, you incremented i
. You're looking at the next element after the one you just entered.
After calling the method once, your array looks like this:
numbers[0] = 1;
numbers[1] = undefined;
and i == 1
.
After calling it again, the array looks like:
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = undefined;
and i == 2
.
Hopefully you can see that this method will always alert undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With