JavaScript Increasing the number in an array

I want to increase the value in an array when I click a JavaScript link

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 as a function

<a href='javascript:go(1)' </a> 

but always warning calls me <undefined

+5
source share
5 answers

This is because you increase the "i"

i++;

right before you put a warning! This way, “i” will refer to the next slot in the array, not the one you just filled.

You can change the alert to use "i-1"

alert(numbers[i - 1]);
+6
source

- , , i. , .

:

numbers[0] = 1;
numbers[1] = undefined;

i == 1.

:

numbers[0] = 1;
numbers[1] = 1;
numbers[2] = undefined;

i == 2.

, , undefined

+7

numbers[0] = 1, i, 1, alert(numbers[1]) undefined, undefined.

alert , . , onclick JS, HTML.

+4

, , :

  • 0.
  • , , ...
  • ... , .
  • , , undefined - , i .

, ?

+4

... ?

"

, !

function go(val){
  numbers[i]=val;
  i++;
}

( i - undefined) - ,

numbers.push(val);

and if you need i to equal what will be the index of the next element of the array is undefined, then

i = numbers.length;

To increase the value, you must first have numerical values ​​for some elements of the array; then your function will need an index whose value will increase

var numbers = [0,0,0,0];

function go(i){
  numbers[i]++;
}

// testing

go(1);
go(3);
go(1);

alert(numbers);

will show 0,2,0,1

But if your goal is to put the value in a new element at the end of the array, just use .push ()

and .length will say how many elements there are; no need to increase i

0
source

All Articles