Add value in Arrays in javascript

Something Like that:
Add value in Arrays

For that you need to create first html code.

JS

function buildFunctions(){
    var arr = [];
    for (var i = 0; i<3; i++){
        arr.push (
            function(){
            document.write(i + '
'); } ) //appned new element in a array and returns the new langth of the array } return arr; } var fs = buildFunctions(); fs[0](); fs[1](); fs[2]();

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”mMpxWE” default_tab=”result” user=”pradeepanvi”]See the Pen Add value in Arrays in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see

3
3
3

3 all times. Something strange?

JS

function buildFunctions2(){
    var arr = [];
    for (var i = 0; i < 3; i++){
        arr.push(
            (function(j){
                return function(){
                    document.write(j + '
'); } }(i)) ) } return arr; } var fs2 = buildFunctions2(); fs2[0](); fs2[1](); fs2[2]();

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”qXpoPB” default_tab=”result” user=”pradeepanvi”]See the Pen Add value in Arrays in javascript 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see

0
1
2

Leave a Reply

Your email address will not be published. Required fields are marked *