Array appending after each onclick and loop in javascript

1.4k views Asked by At

This is the code fragment I have tried:

radio.onclick = function() {
     var pp = e.target.result.split("\n");
    var pq = pp.split('\n'); 
    var pr = []; // array to append each values

    for (var k = 0; k < pq.length; k++) {
        var a = pq[0];  
    }

    pr = a; // I need to create an array which should append again and again
}

In this code, after clicking a radio, a loop generates the value for the 'a' variable, whom it's added to array 'pr'. I want to add the generated value to 'pr' itself after the next on-click.

Is it possible?

3

There are 3 answers

0
m4lt3 On BEST ANSWER

You probably want to do this:

radio.onclick = function() {
    var pq = pp.split('\n'); 
    var pr = []; // array to append each values

    for (var k = 0; k < pq.length; k++) {
        pr.push(pq[k]);  
    }
}

If you need global access to pr just define it outside from radio.onclick.

Edit

even shorter:

radio.onclick = function() {
    var pq = pp.split('\n');
}

or global

var pq = [];
radio.onclick = function() {
   pq = pp.split('\n');
}
2
Nirmi On

Just define the array

pr

globally.

var pr = []; // array to append each values

radio.onclick = function() {
 var pq = pp.split('\n'); 


 for (var k = 0; k < pq.length; k++) {
     var a = pq[0];  
 }

 pr.push(a); // i need to create an array which should append again and again
}

But there you just get the last pq[0]of the loop Hope that helps

0
Sunny On
$(document).ready(function(){var array = new Array(); //Global  declaration   

radio.onclick = function(){ //do stuff here..

//get your value

array.push(your value);

}

});

//if you want to clear the array array.splice();