user3733929
user3733929

Reputation: 47

How add variable to global array in JS

I have a simple code in JS, when i click Button 1 i see in console log 2 variables varData1 and varData2. I would like to add third variable varData3. WHen i click Button2 i expect third value will be in array but i have see nothing. How can i do this ?

var parParams = [];

$('#button1').click(function() {
    parParams = {
        varData1 : "eight",
        varData2 : 7,
    };

console.log(parParams["varData1"]);
console.log(parParams["varData2"]);
console.log(parParams["varData3"]);
}

$('#button2').click(function() {
    parParams['varData3']= 77;
}

Upvotes: 0

Views: 477

Answers (1)

Quentin
Quentin

Reputation: 943697

You have to look at the value after you set it, currently you are looking at it when you click button 1, not button 2.

Note that button 2 adds a value to an existing object while button 1 overwrites the existing array with a new object. (So if you click button 2 and then button 1, you'll overwrite the object containing the varData3 value before you try to look at it).

It sounds like you actually want something more like this:

var parParams = {}; // Object, not array

$('#button1').click(function() {
    // Modify object, don't overwrite it.
    parParams.varData1 = "eight";
    parParams.varData2 = 7;
    examineObject();
}

$('#button2').click(function() {
    parParams['varData3'] = 77;
    examineObject(); // Look at it here, not just when the other button is clicked
}

function examineObject() {
    console.log(parParams);
}

Upvotes: 6

Related Questions