Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Incrementing a number in an array

Tags:

javascript

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'

like image 832
Sudantha Avatar asked Nov 19 '10 17:11

Sudantha


People also ask

How do you increment a value in JavaScript?

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.

What is sum += in JavaScript?

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.

What does i ++ mean in JavaScript?

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.


1 Answers

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

like image 60
Jonathon Faust Avatar answered Sep 28 '22 12:09

Jonathon Faust