0

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;
}
2
  • 1
    you are using array as object , define it like var parParams = {} Commented Aug 26, 2014 at 13:27
  • You see nothing is because there is no console.log in the click event for button 2. Commented Aug 26, 2014 at 13:31

1 Answer 1

6

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works Perfect , thnak You

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.